比较器比较

b1zrtrql  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(154)

这个问题在这里已经有答案了

泛型类型推断不使用方法链接(2个答案)
四年前关门了。
我需要整理一份要点清单。首先我需要比较x值,然后如果x值相等,就比较y值。所以我想我应该用比较的方法:

Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);

但我一直得到这样的信息:不兼容的类型:comparator不能转换为comparator。
我还有其他方法可以做这个比较,而且很有效,但我不明白我做错了什么。

roqulrg3

roqulrg31#

此代码不起作用:

Comparator<Point> cmp = Comparator.<Point> comparingInt(p -> p.x)
                                  .thenComparingInt(p -> p.y);

我只是补充了一句 <Point> 之前 comparingInt ,它显式声明 p 在lambda里。这是必要的,因为由于方法链的原因,java无法推断类型。
另请参见泛型类型推断不使用方法链接?
另一种选择是:

Comparator<Point> cmp = Comparator.comparingDouble(Point::getX)
                                  .thenComparingDouble(Point::getY);

在这里,可以毫无问题地推断出类型。但是,您需要使用双重比较,因为 getX 以及 getY 返回双精度值。我个人更喜欢这种方法。

bbmckpt7

bbmckpt72#

尝试更改:

Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);

Comparator<Point> cmp = Comparator.comparingInt((Point p) -> p.x).thenComparingInt((Point p) -> p.y);

相关问题