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