Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain methods in Comparator.comparing of List in Java 8

Tags:

java

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.
like image 771
Hari Rao Avatar asked Jan 29 '23 19:01

Hari Rao


2 Answers

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.

like image 57
Eugene Avatar answered Feb 02 '23 10:02

Eugene


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.

like image 29
Szymon Stepniak Avatar answered Feb 02 '23 10:02

Szymon Stepniak