Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream sorted method with comparator

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

like image 786
alwayscurious Avatar asked Dec 21 '25 14:12

alwayscurious


1 Answers

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);
like image 84
Lino Avatar answered Dec 24 '25 02:12

Lino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!