在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属性优先排在前面。
上一篇:按照空值优先的降序排列
下一篇:按照空值在末尾排序