Why isn't (Comparator :: reverseOrder) sorting?
Below the Stream expression works great:
Stream<String> s = Stream.of("yellow","blue", "white");
s.sorted(Comparator.reverseOrder())
.forEach(System.out::print);` //yellowwhiteblue
Why isn't the equivalent method compiled with method references?
s.sorted(Comparator::reverseOrder).forEach(System.out::print);
Comparator type does not define reverseOrder (String, String) which is applicable here
source to share
The method reference tells Java to "treat this method as an implementation of the interface of a single method," that is, the method reference must be signed int foo(String,String)
and thus implemented Comparator<String>
.
Comparator.reverseOrder()
doesn't - Returns an instance Comparator
. Because it sorted
looks Comparator
, it can accept the result of a method call, but it cannot use that method as an interface implementation.
source to share
The line of code with a method reference s.sorted (Comparator :: reverseOrder) tells Java that there is a static method with the signature of a trivial method comparator, which means there are two parameters.
The Comparator class only has a static reverseOrder method with no parameters, which causes a compilation error.
source to share