Kotlin对list进行排序的一种方法

今天看了java排序的方法,自己用kotlin写了一个小的list的排序,代码如下。

1.首先定义一个内部类,用于比较list中两个数的大小

inner class User : Comparable {
    var name: String? = null
    var order: Int? = null
    override fun compareTo(other: User): Int {
        return this.order!!.compareTo(other.order!!)
    }
}

 

2.对list进行排序

 

val list = ArrayList()
private fun dataOrder() {

    val user1:User? = User()
    val user2:User? = User()
    val user3:User? = User()
    user1?.name = "a"
    user1?.order = 3

    user2?.name = "b"
    user2?.order = 2

    user3?.name = "c"
    user3?.order = 5

    //此处add user2再add user1
    user1?.let { list.add(it) }
    user2?.let { list.add(it) }
    user3?.let { list.add(it) }
    Collections.sort(list)
    for (u in list) {
        Log.e("sds","paixusuanfa>>>>>>" + u.name)
    }
}

你可能感兴趣的:(Kotlin对list进行排序的一种方法)