如何按两个属性和整理器对对象列表进行排序

K.O*_*.Os 2 functional-programming kotlin

我必须按 lastName 和 firstName 对对象列表进行排序(如果多个对象的 lastName 相同)。我还必须对这些应用 Collat​​or。

假设我可以为一个属性做到这一点:

val collator = Collator.getInstance(context.getResources().getConfiguration().locale)

myList.sortedWith(compareBy(collator, { it.lastName.toLowerCase() }))
Run Code Online (Sandbox Code Playgroud)

但是是否可以将另一个限制也应用到按名字排序?

Ily*_*lya 6

您可以添加另一个排序条件thenBy

val comparator =
        compareBy(collator) { p: Person -> p.lastName.toLowerCase() }
                .thenBy(collator) { p: Person -> p.firstName.toLowerCase() }
val result = myList.sortedWith(comparator)
Run Code Online (Sandbox Code Playgroud)