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
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01