Java 8 流 max() 函数参数类型 Comparator vs Comparable

Java 8 stream max() function argument type Comparator vs Comparable(Java 8 流 max() 函数参数类型 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

基础教程推荐