Kotlin中的数组列表排序

rslzwgfq  于 2023-01-05  发布在  Kotlin
关注(0)|答案(2)|浏览(179)

我有一个ArrayList的ArrayList,我想实现的是,按降序排序(基于最高到最低的列表大小),首先获得最大的列表。
我在java中使用集合做了同样的事情。它在那里工作得很好,但现在我无法在Koltin中实现这一点,我得到了Error.

假设我有class Foo()

private var allHistoryList: ArrayList<ArrayList<Foo>> = arrayListOf()

 /**
             * Sorting array of array list to get Biggest to smallest array List based of size
             */

  Collections.sort(allHistoryList, object: Comparator<ArrayList>{
        override fun compare(var a1, var a2) :Int {
            return a2.size() - a1.size()
        }

    }

  Collections.sort(allHistoryList, object: Comparator<ArrayList>{
                override fun compare(var a1 : ArrayList<*>, var a2 :ArrayList<*>) :Int {
                    return a2.size() - a1.size()
                }

            }

            )
            //end of sorting

             /**
             * Sorting array of array list to get Biggest to smallest array List based of size
             */

            Collections.sort(allHistoryList, new Comparator<ArrayList>() {
                public int compare(ArrayList a1, ArrayList a2) {
                    return a2.size() - a1.size(); // working fine in Java.
                }
            });//end of sorting
jvlzgdj9

jvlzgdj91#

在Kotlin,只有一句话:

allHistoryList.sortByDescending { list -> list.size }

方法sortByDescending使用列表的大小作为选择符来对原始列表进行降序排序,以便在元素之间进行比较。

vltsax25

vltsax252#

导入java实用程序 *
fun main(参数:数组){

val list = ArrayList<CustomObject>()
list.add(CustomObject("Z"))
list.add(CustomObject("A"))
list.add(CustomObject("B"))
list.add(CustomObject("X"))
list.add(CustomObject("Aa"))

var sortedList = list.sortedWith(compareBy({ it.customProperty }))

for (obj in sortedList) {
    println(obj.customProperty)
}

}

相关问题