【问题标题】:How to sort list of objects by two properties and collator如何通过两个属性和整理器对对象列表进行排序
【发布时间】:2019-02-16 10:37:51
【问题描述】:
我必须按姓氏和名字对对象列表进行排序(如果多个对象的姓氏相同)。我还必须对这些应用 Collator。
假设我可以为一个属性做到这一点:
val collator = Collator.getInstance(context.getResources().getConfiguration().locale)
myList.sortedWith(compareBy(collator, { it.lastName.toLowerCase() }))
但是否也可以将另一个限制应用于也按名字排序?
【问题讨论】:
标签:
kotlin
functional-programming
【解决方案1】:
您可以使用thenBy 添加其他排序条件:
val comparator =
compareBy(collator) { p: Person -> p.lastName.toLowerCase() }
.thenBy(collator) { p: Person -> p.firstName.toLowerCase() }
val result = myList.sortedWith(comparator)
【解决方案2】:
最简单的就是在选择器 lambda 中连接两个属性:
myList.sortedWith(
compareBy(collator) { "${it.lastName} ${it.firstName}".toLowerCase() }
)