Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Comparator::reverseOrder and Comparator.reverseOrder() when used in sorted method of stream

What is the difference between Comparator::reverseOrder and Comparator.reverseOrder() when used in sorted method of stream.

    Stream<String> streamText = Stream.of("over the river", "through the woods", "to grandmother's house we go");

This works:

    streamText.filter(n -> n.startsWith("t"))
         .sorted(Comparator.reverseOrder())
         .findFirst().ifPresent(System.out::println);

But this does not compile:

    streamText.filter(n -> n.startsWith("t"))
         .sorted(Comparator::reverseOrder)
         .findFirst().ifPresent(System.out::println);
like image 572
Oro Avatar asked Jan 03 '23 12:01

Oro


1 Answers

Good question!

sorted need a Comparator<T>, right? Comparator<T> is a functional interface. It represents a function that takes 2 arguments and returns an int indicating which argument is greater or whether they are equal.

In the case of Comparator.reverseOrder(), reverseOrder is a method that returns a Comparator<T>. In this case you call the method and it returns a Comparator that can be used as the parameter for sorted. Everything is good.

In the case of Comparator::reverseOrder, you are not calling reverseOrder. Instead, you are passing reverseOrder as a function into sorted. As mentioned above, sorted will accept a function that takes 2 parameters and returns an int, but you are giving it reverseOrder, which takes no arguments and returns a Comparator<T>. See the mismatch here?

Expected: a function that takes 2 parameters and returns an int OR a Comparator<T> object

What you gave it: a function that takes no parameters and returns a Comparator<T>

This results in a compiler error.

like image 102
Sweeper Avatar answered Jan 14 '23 12:01

Sweeper