Vijay Narayanan
Vijay Narayanan

Reputation: 83

Why doesn't sorted(Comparator::reverseOrder) work?

The below Stream expression works perfectly fine:

Stream<String> s = Stream.of("yellow","blue", "white");
 s.sorted(Comparator.reverseOrder())
  .forEach(System.out::print);` //yellowwhiteblue

Why doesn't the equivalent one with method references compile?

s.sorted(Comparator::reverseOrder).forEach(System.out::print);

The type Comparator does not define reverseOrder(String, String) that is applicable here

Upvotes: 4

Views: 1376

Answers (3)

Hari Rao
Hari Rao

Reputation: 3260

Stream<String> s=Stream.of("yellow","blue", "white");
        s.sorted(String::compareTo)
                .forEach(System.out::println);

if you still want to use a method reference then the above will work. This seems to be a common question in OCP Java 8 certification.

Upvotes: 0

edwindh
edwindh

Reputation: 109

The line of code with method reference s.sorted(Comparator::reverseOrder) is telling Java that there is a static method with the signature of a trivial method comparator, it means with two parameters.

The class Comparator has only the static method reverseOrder without parameters, that's the reason of the compiling error.

Upvotes: 3

A method reference is telling Java "treat this method as the implementation of a single-method interface"--that is, the method reference should have the signature int foo(String,String) and thus implement Comparator<String>.

Comparator.reverseOrder() doesn't--it returns a Comparator instance. Since sorted is looking for a Comparator, it can take the result of the method call, but it can't use that method as the interface implementation.

Upvotes: 7

Related Questions