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);
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>
objectWhat you gave it: a function that takes no parameters and returns a
Comparator<T>
This results in a compiler error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With