gpt4 book ai didi

java - 我可以从没有显式变量的 lambda 表达式创建 Comparator 对象吗?

转载 作者:搜寻专家 更新时间:2023-11-01 02:20:14 25 4
gpt4 key购买 nike

我还不熟悉 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))));

谢谢。

最佳答案

首先,您的直接错误:您忘记在您的转换类型周围放置括号。尝试:

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));

关于java - 我可以从没有显式变量的 lambda 表达式创建 Comparator 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47478389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com