【问题标题】:How to sort a list of object type如何对对象类型列表进行排序
【发布时间】: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) -&gt; Double.compare(p1.getD(), p2.getD())
  • 仅供参考:comment by michalk 所示,当您调用 方法时,语法为xxx.method()。构建方法引用时,语法为xxx::method,没有()
  • 第一个代码示例肯定不会产生您描述的错误。如果getD() 返回原始类型double,你会得到类似“double cannot be dereferenced”的信息。

标签: java list collections comparator


【解决方案1】:

使用 java 8 方法引用,不能使用括号

代替 Player::getD() 使用 Player::getD

Collections.sort(PlayerList,Comparator.comparing(Player::getD)); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2021-12-12
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多