I wrote some simple code like below. This class works fine without any errors.
public class Test {
public static void main(String[] args) {
List&
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.