java 比较器比较Int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36253973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparator comparingInt
提问by fwend
I need to sort a list of Points. First I need to compare the x value, then if the x values are equal, the y value. So I thought I'd use the thenComparing method:
我需要对点列表进行排序。首先我需要比较 x 值,然后如果 x 值相等,则 y 值。所以我想我会使用 thenComparing 方法:
Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);
But I keep getting the message: Incompatible types: Comparator<Object> cannot be converted to Comparator<Point>.
但我不断收到消息:不兼容的类型:Comparator<Object> 无法转换为 Comparator<Point>。
There are other ways I can make this comparison, and it works, but I don't understand what I'm doing wrong here.
我还有其他方法可以进行这种比较,并且它有效,但我不明白我在这里做错了什么。
回答by Stefan Dollase
This code does work:
此代码确实有效:
Comparator<Point> cmp = Comparator.<Point> comparingInt(p -> p.x)
.thenComparingInt(p -> p.y);
I only added <Point>
before comparingInt
, which explicitly declares the type of p
in the lambda. This is necessary, since Java cannot infer the type, due to the method chain.
我只添加了<Point>
before comparingInt
,它p
在 lambda 中明确声明了 的类型。这是必要的,因为由于方法链的原因,Java 无法推断类型。
See also Generic type inference not working with method chaining?
另请参阅通用类型推断不适用于方法链?
Here is another alternative:
这是另一种选择:
Comparator<Point> cmp = Comparator.comparingDouble(Point::getX)
.thenComparingDouble(Point::getY);
Here, the type can be inferred without any problems. However, you need to use the double comparison, because getX
and getY
return double values. I personally prefer this approach.
在这里,可以毫无问题地推断类型。但是,您需要使用双重比较,因为getX
并getY
返回双重值。我个人更喜欢这种方法。
回答by Darshan Mehta
Try changing:
尝试改变:
Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);
to
到
Comparator<Point> cmp = Comparator.comparingInt((Point p) -> p.x).thenComparingInt((Point p) -> p.y);