I have the following Objects
Class Trade{
private Integer tradeId;
private Event eventId;
private Integer tradeVersion;
}
Class Event{
private Integer value;
}
Comparator.comparing(Trade::getEventId().getValue())
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?
Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue)
but no joy.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With