The api for Stream.max
requires an argument of type Comparator<? super T>
, and for Comparator
, the only abstract method is
int compare(T o1, T o2)
but Double::compareTo
, the compareTo
api is
public int compareTo(Double anotherDouble)
why just provide one argument, so why can Double::compareTo
use as argument of Stream
Optional<T> max(Comparator<? super T> comparator)
The below
MyComparator
implement aComparator
. It takes two arguments.It's the same as the lambda expression
(d1,d2) -> d1.compareTo(d2)
and the same as the method reference
Double::compareTo
The method reference is the same because
d1
is aDouble
, so Java assumes thecompareTo
method is to be called on the firstDouble
. The other argumentd2
becomes the argument for the method called. This is also very nicely explained by @Andronicus.The 3 variants in this example are equivalent:
Check out the oracle documentation. This is a reference to an instance method. This means, it can be considered as
BiFunction
, that takes the instance as the first argument.In Java Language Specification (15.13.3) we can read, that:
The interesting part is bolded by me.
u can use one of these 2 methods to compare Double