Java 8 stream max() function argument type Comparator vs Comparable(Java 8 流 max() 函数参数类型 Comparator vs Comparable)
问题描述
我写了一些简单的代码,如下所示.这个类工作正常,没有任何错误.
I wrote some simple code like below. This class works fine without any errors.
public class Test {
public static void main(String[] args) {
List<Integer> intList = IntStream.of(1,2,3,4,5,6,7,8,9,10).boxed().collect(Collectors.toList());
int value = intList.stream().max(Integer::compareTo).get();
//int value = intList.stream().max(<Comparator<? super T> comparator type should pass here>).get();
System.out.println("value :"+value);
}
}
正如代码注释所示,max()
方法应该传递 Comparator? 类型的参数?超级整数>
.
As the code comment shows the max()
method should pass an argument of type Comparator<? super Integer>
.
但是 Integer::compareTo
实现了 Comparable
接口 - 不是 Comparator
.
But Integer::compareTo
implements Comparable
interface - not Comparator
.
public final class Integer extends Number implements Comparable<Integer> {
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
}
这如何工作?max()
方法说它需要一个 Comparator
参数,但它适用于 Comparable
参数.
How can this work? The max()
method says it needs a Comparator
argument, but it works with Comparable
argument.
我知道我误解了一些东西,但我现在知道是什么了.谁能解释一下?
I know I have misunderstood something, but I do now know what. Can someone please explain?
推荐答案
int value = intList.stream().max(Integer::compareTo).get();
上面的代码片段在逻辑上等价于:
The above snippet of code is logically equivalent to the following:
int value = intList.stream().max((a, b) -> a.compareTo(b)).get();
这在逻辑上也等价于以下内容:
Which is also logically equivalent to the following:
int value = intList.stream().max(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
}).get();
Comparator
是一个函数式接口,可以用作 lambda 或方法引用,这就是您的代码编译和执行成功的原因.
Comparator
is a functional interface and can be used as a lambda or method reference, which is why your code compiles and executes successfully.
我建议阅读 Oracle 的方法参考教程(他们使用比较两个对象的示例)以及 §15.13.方法引用表达式 以了解其工作原理.
I recommend reading Oracle's tutorial on Method References (they use an example where two objects are compared) as well as the Java Language Specification on §15.13. Method Reference Expressions to understand why this works.
这篇关于Java 8 流 max() 函数参数类型 Comparator vs Comparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 流 max() 函数参数类型 Comparator vs Comparable
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01