The Stream
class in Java 8 defines a max
method that requires a Comparator
argument. Here is the method signature:
Optional<T> max(Comparator<? super T> comparator)
Comparator
is a functional interface that has an abstract compare
method with this signature. Notice compare
requires 2 arguments.
int compare(T o1, T o2)
The Comparable
interface has an abstract compareTo
method with this signature. Notice compareTo
requires only 1 argument.
int compareTo(T o)
In Java 8, the following code works perfectly. However, I expected a compilation error like, "the Integer class does not define compareTo(Integer, Integer)".
int max = Stream.of(0, 4, 1, 5).max(Integer::compareTo).get();
Can someone help explain why it's possible to pass an instance of Comparable
to a method that expects an instance of Comparator
even though their method signatures are not compatible?
That's a nice feature about method references. Note that Integer::compareTo
is an instance method. You need two Integer
objects to call it. One on the left side (the target object), and one on the right side (the first and only parameter).
So Integer::compareTo
is a method reference for a method, that expects two Integer
objects and returns an int
. Comparator<Integer>
is a functional interface for functions, that expect two Integer
objects and return an int
. That's the reason why it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With