在Kotlin中,可以使用sortedWith
函数来对对象数组进行排序。为了按照空值优先,然后按降序排序,可以传递一个自定义的Comparator
对象给sortedWith
函数。
以下是一个示例代码:
data class Person(val name: String, val age: Int?)
fun main() {
val people = arrayOf(
Person("Alice", 25),
Person("Bob", null),
Person("Charlie", 30),
Person("Dave", 20),
Person("Eve", null)
)
val sortedPeople = people.sortedWith(compareByDescending { it.age }.thenBy { it.name })
sortedPeople.forEach { println(it) }
}
在上面的代码中,我们定义了一个Person
类,它有一个name
属性和一个可为空的age
属性。
然后我们创建了一个包含多个Person
对象的数组people
。其中,Bob
和Eve
的age
属性是空值。
我们使用sortedWith
函数来对people
数组进行排序。在compareByDescending
函数中,我们传入了一个lambda表达式,用于比较Person
对象的age
属性,并以降序排序。然后,我们使用thenBy
函数来按照name
属性进行排序。
最后,我们使用forEach
函数遍历排序后的数组,并打印每个Person
对象的信息。
输出结果为:
Person(name=Charlie, age=30)
Person(name=Alice, age=25)
Person(name=Dave, age=20)
Person(name=Bob, age=null)
Person(name=Eve, age=null)
可以看到,数组中的对象首先按照降序排列了age
属性,然后按照name
属性进行排序。空值(null)的age
属性优先排在前面。
上一篇:按照空值优先的降序排列
下一篇:按照空值在末尾排序