I wrote some simple code like below. This class works fine without any errors.
public class Test {
public static void main(String[] args) {
List 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 type should pass here>).get();
System.out.println("value :"+value);
}
}
As the code comment shows the max() method should pass an argument of type Comparator super Integer>.
But Integer::compareTo implements Comparable interface - not Comparator.
public final class Integer extends Number implements Comparable {
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
}
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() {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
}).get();
Comparator is a functional interface and can be used as a lambda or method reference, which is why your code compiles and executes successfully.
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.