Reputation: 1161
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)
}
Upvotes: 3
Views: 4473
Reputation: 4753
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).
Upvotes: 9
Reputation: 3025
Try this
companyList = companyList.sortedWith(compareBy { it.order })
You can check the document here https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sorted-with.html
Upvotes: 1