如何通过两个属性和排序规则对对象列表进行排序 [英] How to sort list of objects by two properties and collator

查看:98
本文介绍了如何通过两个属性和排序规则对对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to sort list of object by lastName and firstName (if case there is the same lastName for multiple objects). I must also apply Collator to those.

假设我可以对一个属性执行此操作:

Suppose I can do that for one property:

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

myList.sortedWith(compareBy(collator, { it.lastName.toLowerCase() }))

但是是否可以将另一个限制也应用于按firstName排序?

But is it possible to apply also to that another restriction to also sort by firstName?

推荐答案

您可以使用thenBy添加其他排序条件:

You can add another sort criteria with thenBy:

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

这篇关于如何通过两个属性和排序规则对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆