示例:按属性对自定义对象 ArrayList 进行排序
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)
}
}
public class CustomObject(val customProperty: String) {
}
运行程序后,输出将是
A Aa B X Z
在上面的程序中,我们定义了一个具有 `String` 属性 `customProperty` 的 `CustomObject` 类。
在 `main()` 方法中,我们创建了一个自定义对象列表 `list`,其中包含 5 个对象。
为了根据属性对列表进行排序,我们使用了 `list` 的 `sortedWith()` 方法。`sortedWith()` 方法接受一个比较器 `compareBy`,该比较器比较每个对象的 `customProperty` 并进行排序。
排序后的列表存储在变量 `sortedList` 中。
以下是等效的 Java 代码:Java程序按属性对自定义对象 ArrayList 进行排序。