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