sorting - Java集合排序通过比较器给出错误
问题描述
我尝试使用 Collections 对 Java ArrayList 进行排序,但它不起作用,即使我尝试遵循其他问题的代码。
我有一个名为 PcdPoint 的类,它具有 getScore() 和 getType() 方法,其中 getScore() 返回一个双精度数,而 getType() 返回一个整数。(不是原子的)
以下代码应该可以工作,但它给了我一个错误:“无法推断类型 <any>”
Collections.sort(pointList,
Comparator.comparing((PcdPoint a, PcdPoint b) -> a.getScore() - b.getScore())
.thenComparing((PcdPoint a, PcdPoint b) -> a.getType() - b.getType()));
所以我尝试查找文档并尝试这样做
Collections.sort(pointList,
Comparator<PcdPoint>.comparing((a, b) -> a.getScore() - b.getScore())
.thenComparing((a, b) -> a.getType() - b.getType()));
和
Collections.sort(pointList,
Comparator.comparing((a, b) -> a.getScore() - b.getScore())
.thenComparing((a, b) -> a.getType() - b.getType()));
但这些似乎都不起作用。
解决方案
如果您想先按分数排序,然后按类型排序,您的比较器应该如下所示。
Collections.sort(pointList,
Comparator.comparingDouble(PcdPoint::getScore)
.thenComparingInt(PcdPoint::getType));
推荐阅读
- python - 向用户 discord.py 的 DM 发送消息时出错
- javascript - 重新渲染后 React Refs 为空
- single-sign-on - Laravel 临时 SSO 方法
- java - Oracle 19c JDBC(即时客户端 basiclite)驱动程序问题
- javascript - 找不到此 switch 语句的问题所在,它在我的 VS 代码编辑器中的 case 语法中始终显示红色下划线
- angular - 在 BsModalRef 中模拟 modal.content.onClose.subscribe
- python - 在django中调用一对一模型时如何调用应用程序名称?
- flutter - 未来
登录无法编译应用程序 - mongodb - 我正在使用 mongodb 聚合,它期望不同的输出,但没有得到所需的输出
- javascript - 为什么即使我有多次交易,产品收入仍然为 0(Google Analytics Enhanced Ecommerce)