4

I have an ArrayList of ArrayList what I want to achieve is, to sort them in descending order (based on the Highest to lowest List size ) to get the largest first and onwards.

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

Consider I've a 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
3
  • Which error are you getting? Commented Mar 30, 2020 at 7:59
  • What's the type of allHistoryList? Commented Mar 30, 2020 at 8:31
  • consider it as Foo for time being.? @GiorgioAntonioli and its not generic List. Commented Mar 30, 2020 at 8:35

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

Comments

1
import java.util.*

fun main(args: Array<String>) {

    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)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.