【问题标题】:Sort collection by multiple fields in Kotlin [duplicate]在Kotlin中按多个字段对集合进行排序[重复]
【发布时间】:2016-09-12 13:15:19
【问题描述】:

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

来自 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

【问题讨论】:

  • 我也是,来自 C# 世界,也有同样的问题;谢谢你的提问!

标签: kotlin


【解决方案1】:

sortedWith + compareBy(采用 lambda 的可变参数)可以解决问题:

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

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

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

【讨论】:

  • 在 Kotlin 1.2.42 中,两种解决方案都会出现编译错误:Cannot choose among the following candidates without completing type inference: public fun &lt;T&gt; compareBy(vararg selectors: (???) → Comparable&lt;*&gt;?): kotlin.Comparator&lt;???&gt; defined in kotlin.comparisons public fun &lt;T&gt; compareBy(vararg selectors: (T) → Comparable&lt;*&gt;?): kotlin.Comparator&lt;T&gt; /* = java.util.Comparator&lt;T&gt; */ defined in kotlin.comparisons
  • @arslancharyev31 This seems to be reported as a bug。它只显示在 IDE 中;我的gradle build 成功了。
  • 这是升序排序,如何降序排序?
  • @Chandrika compareByDescending
  • compareByDescending 将反转所有功能。如果您只想使用一个字段进行降序排列,请在前面打一个-(减号),就像这样{-it.age}
【解决方案2】:

使用sortedWith 对带有Comparator 的列表进行排序。

然后您可以使用多种方式构建比较器:

  • compareBy, thenBy 在调用链中构造比较器:

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

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

【讨论】:

  • 谢谢,这就是我要找的!我对 kotlin 有点陌生,为什么您需要在第一个要点中使用 compareBy&lt;Person&gt; 而不是 compareBy
  • @Aneem,Kotlin 编译器有时无法推断类型参数,需要手动指定。一种这样的情况是当需要一个泛型类型时,您想要传递泛型函数调用链的结果,例如compareBy&lt;Person&gt; { it.age }.thenBy { it.name }.thenBy { it.address }。第二点,只有一个函数调用,没有调用链:compareBy({ it.age }, { it.name }, { it.address })
  • 如何添加不区分大小写?
  • 你有解决办法吗? @康拉德
  • @KoustuvGanguly 也许这会帮助你stackoverflow.com/questions/52284130/…
猜你喜欢
  • 2013-09-10
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多