在Kotlin中按多个字段排序收集
比方说,我有一个人名列表,我需要首先按年龄,然后按名称排序。
来自C#的背景,我可以通过使用LINQ轻松实现这种语言:
var list=new List<Person>(); list.Add(new Person(25, "Tom")); list.Add(new Person(25, "Dave")); list.Add(new Person(20, "Kate")); list.Add(new Person(20, "Alice")); //will produce: Alice, Kate, Dave, Tom var sortedList=list.OrderBy(person => person.Age).ThenBy(person => person.Name).ToList();
如何使用Kotlin完成这个工作?
这是我试过的(这显然是错误的,因为第一个“sortedBy”子句的输出被第二个输入覆盖,导致列表按名称排序)
val sortedList = ArrayList(list.sortedBy { it.age }.sortedBy { it.name })) //wrong
sortedWith
+ compareBy
(采用可变compareBy
的lambda表达式)诀窍:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
您还可以使用更简洁的可调用参考语法:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
使用sortedWith
对Comparator
sortedWith
进行排序。
然后你可以用几种方法构造一个比较器:
-
compareBy
,thenBy
在调用链中构造比较器:list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
-
compareBy
有一个重载函数,它有多个函数:list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))