Sorting ArrayList in Koltin

北城以北 提交于 2020-06-29 04:40:06

问题


I've have a ArrayList of ArrayList what I want to achive is , to sort them in decending order (based on Highest to lowest List size ) to get largest first and onwards.

I did same thing in java using Collections.It worked perfectly fine there but now I'm unable to achieve this in Koltin i'm getting ERROR.

Consider I've have 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

回答1:


In Kotlin, it's just one line:

allHistoryList.sortByDescending { list -> list.size }

The method sortByDescending mutates the original list sorting it descending using the size of the list as selector to make the comparison between elements.



来源:https://stackoverflow.com/questions/60926218/sorting-arraylist-in-koltin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!