【问题标题】:How do I chain groovy's spaceship operator for multilevel sorting?如何链接 groovy 的宇宙飞船运算符进行多级排序?
【发布时间】:2023-03-30 23:15:01
【问题描述】:

Groovy 具有宇宙飞船运算符<=>,它提供了一种实现比较的简单方法。我怎样才能以更时髦的方式链接它,然后是下面的代码?在这个例子中,我想先按价格比较商品,如果两者价格相同,再按名称比较。


class Item implements Comparable {
  int price
  String name

  int compareTo(Item other) {
    int result = price <=> other.price
    if (result == 0) {
      result = name <=> other.name
    }
    return result
  }
}

【问题讨论】:

    标签: groovy chaining spaceship-operator


    【解决方案1】:

    由于根据 Groovy Truth,如果两者相等且 0 为假,则宇宙飞船运算符 &lt;=&gt; 返回 0,因此您可以使用 elvis 运算符 ?: 有效地链接您的排序标准。

    
    class Item implements Comparable {
      int price
      String name
    
      int compareTo(Item other) {
        price <=> other.price ?: name <=> other.name
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2011-03-04
      • 2010-11-25
      • 2010-10-24
      • 1970-01-01
      • 2021-07-27
      • 2019-08-10
      • 2012-09-16
      相关资源
      最近更新 更多