原文: https://www.programiz.com/kotlin-programming/examples/sort-custom-objects-property
在此程序中,您将学习按照 Kotlin 中给定属性对自定义对象的ArrayList进行排序。
示例:按属性对自定义对象的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) {}
运行该程序时,输出为:
AAaBXZ
在上面的程序中,我们定义了一个CustomObject类,它带有String属性,即customProperty。
在main()方法中,我们创建了以 5 个对象初始化的自定义对象list的ArrayList。
为了使用属性对列表进行排序,我们使用list的sortedWith()方法。sortedWith()方法采用比较器compareBy,该比较器比较每个对象的customProperty并将其排序。
然后将已排序的列表存储在变量sortedList中。
这里是等效的 Java 代码: Java 程序:通过属性对自定义对象的ArrayList进行排序。
