[英]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;
}
Comparator.comparing(Trade::getEventId().getValue())
Comparator.comparing(Trade::getEventId().getValue())
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是否可行?
Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue)
but no joy. Comparator.comparing(Trade::getEventId).thenComparing(Event::getValue)
但没有快乐。 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.