简体   繁体   English

Comparator中的链方法。比较Java 8中的List

[英]Chain methods in Comparator.comparing of List in Java 8

I have the following Objects 我有以下对象

Class Trade{
   private Integer tradeId;
   private Event  eventId;
   private Integer tradeVersion;
}

Class Event{
  private Integer value;
}
  1. For the above scenario I am trying to write something like Comparator.comparing(Trade::getEventId().getValue()) 对于上面的场景,我试着写一些像Comparator.comparing(Trade::getEventId().getValue())
  2. The above did not work 以上都行不通
  3. So for now I went with the usual lambda which is the following 所以现在我选择了通常的lambda,如下所示

    someList.sort((Trade o1, Trade o2) -> o1.getEventId().getValue().compareTo(o2.getEventId().getValue())) ; someList.sort((Trade o1, Trade o2) -> o1.getEventId().getValue().compareTo(o2.getEventId().getValue())) ;

and it worked but curious to know if #1 is possible? 它很有用但很想知道#1是否可行?

  1. Tried Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue) but no joy. 尝试过Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue)但没有快乐。
  2. Note that both of these classes are third party so I cannot alter them. 请注意,这两个类都是第三方,所以我不能改变它们。

Expression Comparator.comparing(Trade::getEventId().getValue()) does not work, because this is invalid use of method reference . Expression Comparator.comparing(Trade::getEventId().getValue())不起作用,因为这是无效的方法引用 With :: operator you can refer to a single method, like Trade::getEventId . 使用::运算符,您可以引用单个方法,如Trade::getEventId This is an equivalent for following lambda expression: 这与以下lambda表达式等效:

trade -> trade.getEventId()

Although you may try using following Function<Trade, Integer> represented as a following lambda expression: 虽然您可以尝试使用以下Function<Trade, Integer>表示为以下lambda表达式:

(Function<Trade, Integer>) trade -> trade.getEventId().getValue()

Then your comparator could be defined as: 然后您的比较器可以定义为:

Comparator.comparing((Function<Trade, Integer>) trade -> trade.getEventId().getValue())

PS: casting to Function<Trade, Integer> can be avoided probably. PS:可能会避免转换为Function<Trade, Integer>

It's as easy as : 它很简单:

trades.sort(Comparator.comparingInt(x -> x.getEventId().getValue()));

Also notice that your version with Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue) would semantically mean that you are first sorting by eventId then by value which looks like not what you want in the first place. 另请注意,使用Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue)在语义上意味着您首先eventId排序,然后按value看起来不是您想要的value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM