假设我有一个人员列表,我需要按年龄排序,然后按姓名排序.
来自C#-background,我可以使用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();
Run Code Online (Sandbox Code Playgroud)
如何使用Kotlin实现这一目标?
这是我尝试过的(显然是错误的,因为第一个"sortedBy"子句的输出被第二个被覆盖,导致列表仅按名称排序)
val sortedList = ArrayList(list.sortedBy { it.age }.sortedBy { it.name })) //wrong
Run Code Online (Sandbox Code Playgroud)
Ale*_*lov 321
sortedWith
+ compareBy
(采取一系列lambda)做法:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
Run Code Online (Sandbox Code Playgroud)
您还可以使用更简洁的可调用引用语法:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
Run Code Online (Sandbox Code Playgroud)
hot*_*key 99
使用sortedWith
排序与列表Comparator
.
然后,您可以使用以下几种方法构建比较器:
list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
Run Code Online (Sandbox Code Playgroud)compareBy
有一个过载,需要多个功能:
list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
67172 次 |
最近记录: |