GPH*_*GPH 2 arrays sorting android kotlin
我使用下面的sortwith方法对ArrayList进行排序,我想它将排序顺序从小数到大数。例如10,9,8,7,6 .... 0。但是结果不是我所期望的。请帮助解决此问题。
companyList.add(companyReg)
companyList.sortedWith(compareBy { it.order })
for (obj in companyList) {
println("order number: "+obj.order)
}
Run Code Online (Sandbox Code Playgroud)
请参阅以下示例:
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) }
}
Run Code Online (Sandbox Code Playgroud)
为什么这样工作?因为在Kotlin中,大多数收藏都是不可变的。并且collection.sortedWith(...)是一个扩展函数,它返回集合的排序后的副本,但实际上您忽略了此结果。
您可以使用Ofc使用其他方法修改集合(例如.sort())或Collections.sort(collection, comparator)。这种排序方式不需要分配新的集合(因为没有新的集合,所以只能修改当前集合)。