我还不熟悉Java中的lambda表达式。
可以
//create a comparator object using a Lambda expression
Comparator<Double> compareDouble = (d1, d2) -> d1.compareTo(d2);
//Sort the Collection in this case 'testList' in reverse order
Collections.sort(testList, Collections.reverseOrder(compareDouble));
在没有明确创建变量compareDouble
?
我尝试了以下内容,但为什么它不起作用?
//Sort the Collection in this case 'testList' in reverse order
Collections.sort(testList, Collections.reverseOrder(new Comparator<Double> ((d1, d2) -> d1.compareTo(d2))));
感谢。
答案 0 :(得分:2)
首先,您的即时错误:您忘记在您的投射类型周围放置括号。尝试:
Collections.sort(testList, Collections.reverseOrder( (Comparator<Double>) ((d1, d2) -> d1.compareTo(d2))));
编辑:上述错误是当问题没有new
时所以看起来像是演员。
此外,Java的类型推断将在没有将lambda表达式显式转换为必要的函数类型的情况下工作。尝试:
Collections.sort(testList, Collections.reverseOrder( (d1, d2) -> d1.compareTo(d2) ));
如果在这种情况下已经存在比较操作,您可以使用方法参考使其更简单:
Collections.sort(testList, Collections.reverseOrder(Double::compare));
答案 1 :(得分:2)
Double
已经实现Comparable
,因此您可以使用零参数reverseOrder()
重载:
testList.sort(Collections.reverseOrder());
或者您可以撤消自定义比较器:
testList.sort((d1, d2) -> d2.compareTo(d1));
答案 2 :(得分:1)
我会选择类似的东西:
Collections.sort(testList, Comparator.comparingDouble(Type::getDoubleValue).reversed());
Type
是您班级的名称,getDoubleValue
是double
值用作排序键。
另一个较短的选择。
testList.sort(Comparator.comparingDouble(Type::getDoubleValue).reversed());
修改强>
我想我误解了你目前的问题。然而,将您当前的解决方案改为:
Collections.sort(testList, Collections.reverseOrder((e, a) -> e.compareTo(a)));
就够了。
只需将您分配给变量compareDouble
的行为转移到reverseOrder
方法中即可。