首页 文章

按Kotlin中的多个字段对集合进行排序[重复]

提问于
浏览
115

这个问题在这里已有答案:

假设我有一个人员列表,我需要按年龄排序,然后按姓名排序 .

来自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();

如何使用Kotlin实现这一目标?

这就是我尝试过的(显然是错误的,因为第一个“sortedBy”子句的输出被第二个子句覆盖,导致列表仅按名称排序)

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

2 回答

  • 65

    使用sortedWith使用 Comparator 对列表进行排序 .

    然后,您可以使用以下几种方法构建比较器:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
    • compareBy有一个需要多个函数的重载:
    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    
  • 205

    sortedWith compareBy(采取一系列lambda)做法:

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

    您还可以使用更简洁的可调用引用语法:

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

相关问题