在 Kotlin 中按多个字段对集合进行排序 [英] Sort collection by multiple fields in Kotlin

查看:42
本文介绍了在 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(使用 lambda 的可变参数)来解决这个问题:

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 中按多个字段对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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