androidarrayssortingkotlin

kotlin Android sortwith Array issue


I use the below sortwith method to sort my ArrayList, I suppose it will sort the order number from small number to big number. Such as 10,9,8,7,6....0. But the result is not what I expected.Please kindly help to solve this issue.

companyList.add(companyReg)
companyList.sortedWith(compareBy { it.order })

for (obj in companyList) {
    println("order number: "+obj.order)
}

Println result enter image description here


Solution

  • See this example:

    fun main(args: Array<String>) {
        val xx = ArrayList<Int>()
        xx.addAll(listOf(8, 3, 1, 4))
        xx.sortedWith(compareBy { it })
    
        // prints 8, 3, 1, 4
        xx.forEach { println(it) }
    
        println()
    
        val sortedXx = xx.sortedWith(compareBy { it })
        // prints sorted collection
        sortedXx.forEach { println(it) }
    }
    

    In Kotlin, most collections are immutable. And collection.sortedWith(...) is an extension function which returns a sorted copy of your collection, but in fact you ignore this result.

    Of course, you can use other methods modifying collections (like .sort()), or Collections.sort(collection, comparator). This way of sorting doesn't require assigning new collection (because there is no new collection, only current is modified).