I don't understand why code1 works but code2 doesn't compile. Please explain.
//Code1:
Stream<String> s = Stream.of("AA", "BB");
s.sorted(Comparator.reverseOrder())
.forEach(System.out::print);
//Code2:
Stream<String> s = Stream.of("AA", "BB");
s.sorted(Comparator::reverseOrder)
.forEach(System.out::print);
The difference between the two is code1 uses Comparator.reverseOrder() while code2 uses Comparator::reverseOrder
Because the first example is a factory-method so when you inspect it, you see that you get a comparator back.
But the second one is a method-reference which you could write like this:
Stream<String> s = Stream.of("AA", "BB");
s.sorted(() -> Comparator.reverseOrder()) // no semantic difference!
.forEach(System.out::print);
But it has a whole different meaning because this time you are given Stream#sorted() a Supplier<Comparator<?>> but it just needs a Comparator<?>
Small Sidenote: Don't store streams in variables, use them directly. So i would suggest you just write:
Stream.of("AA", "BB")
.sorted(Comparator.reverseOrder())
.forEach(System.out::print);
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