【发布时间】:2020-02-23 10:31:00
【问题描述】:
Player 类已在前面定义。我想根据特定属性对 Player 类型的对象列表进行排序。但是我收到以下语句的错误:')'
Comparator <Player> compareBydefensiveDuel= (Player p1, Player p2)->(p1.getD().compareTo(p2.getD()));
我也尝试过以下语句:
Collections.sort(PlayerList,Comparator.comparing(Player ::getD());
PlayerList.sort(Comparator.comparingDouble(Player::getD()));
在所有这些情况下,它都要求在 Player 之后添加 ')'。如何解决?
【问题讨论】:
-
Collections.sort(PlayerList,Comparator.comparing(Player::getD)); -
getD()的返回类型是什么?如果Double,那么您的代码应该可以正常工作。如果double,那么你需要这个:(Player p1, Player p2) -> Double.compare(p1.getD(), p2.getD()) -
仅供参考: 如comment by michalk 所示,当您调用 方法时,语法为
xxx.method()。构建方法引用时,语法为xxx::method,没有() -
第一个代码示例肯定不会产生您描述的错误。如果
getD()返回原始类型double,你会得到类似“double cannot be dereferenced”的信息。
标签: java list collections comparator