简体   繁体   中英

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())
  2. The above did not work
  3. So for now I went with the usual lambda which is the following

    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. Tried Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue) but no joy.
  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 . With :: operator you can refer to a single method, like Trade::getEventId . This is an equivalent for following lambda expression:

trade -> trade.getEventId()

Although you may try using following Function<Trade, Integer> represented as a following lambda expression:

(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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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