本文介绍了按Kotlin中的多个字段对集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个人"列表,我需要先按年龄"分类,然后再按名称"分类.

Let's say I have a list of People which I need to sort by Age first and then by Name.

从C#的背景出发,我可以使用LINQ以上述语言轻松实现这一目标:

Coming from a C#-background, I can easily achieve this in said language by using 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做到这一点?

How does one accomplish this using Kotlin?

这是我尝试过的方法(这显然是错误的,因为第一个"sortedBy"子句的输出被第二个子句覆盖,从而导致仅按名称对列表进行排序)

This is what I tried (it's obviously wrong since the output of the first "sortedBy" clause gets overridden by the second one which results in a list sorted by Name only)

val sortedList = ArrayList(list.sortedBy { it.age }.sortedBy { it.name })) //wrong

推荐答案

sortedWith + compareBy (采用可变参数的lambdas)做到这一点:

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

您还可以使用更为简洁的可调用参考语法:

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

这篇关于按Kotlin中的多个字段对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:18