Suppose I have a stream of Strings:
Stream<String> stream = Stream.of("c","a","b");
This works OK:
stream.sorted(Comparator.reverseOrder())
But using alternative syntax doesn't:
stream.sorted(Comparator::reverseOrder)
^
Bad return type in method reference: cannot convert Comparator<T> to int
When I Ctrl+Left Click in my IDE both take me to the same static method returning a Comparator in Comparator
class:
public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {
return Collections.reverseOrder();
}
One book explains:
Comparator is a functional interface. This means that we can use method references or lambdas to implement it. The Comparator interface implements one method that takes two String parameters and returns an int . However, Comparator::reverseOrder doesn’t do that. It is a reference to a function that takes zero parameters and returns a Comparator . This is not compatible with the interface. This means that we have to use a method and not a method reference.
But I don't understand it.