加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 比较器比较

发布时间:2020-12-15 00:57:56 所属栏目:Java 来源:网络整理
导读:参见英文答案 Generic type inference not working with method chaining?1个 我需要对点列表进行排序.首先,我需要比较x值,然后如果x值相等,则y值.所以我以为我会使用thenComparing方法: ComparatorPoint cmp = Comparator.comparingInt(p - p.x).thenCompa
参见英文答案 > Generic type inference not working with method chaining?1个
我需要对点列表进行排序.首先,我需要比较x值,然后如果x值相等,则y值.所以我以为我会使用thenComparing方法:
Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);

但我一直收到消息:不兼容的类型:比较器<对象>无法转换为比较器< Point>.

还有其他方法我可以进行这种比较,它有效,但我不明白我在这里做错了什么.

解决方法

这段代码确实有效:
Comparator<Point> cmp = Comparator.<Point> comparingInt(p -> p.x)
                                  .thenComparingInt(p -> p.y);

我只添加了< Point>在comparisonInt之前,它明确地声明了lambda中p的类型.这是必要的,因为Java不能推断类型,因为方法链.

另见Generic type inference not working with method chaining?

这是另一种选择:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读