Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 470
GPH Avatar asked Jun 08 '26 17:06

GPH


1 Answers

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

like image 116
Cililing Avatar answered Jun 10 '26 08:06

Cililing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!