Suppose that you see the #Java code like this on review. What's your primary reaction? Do you like it? github.com/PeterMen/elast…

This code snippet is indeed funny: list = list .stream().sorted((o1, o2) -> -1).toList(); The comparator clearly violates the comparator specification, both reflexivity (return 0 for equal elements) and antisymmetry (swapping args should change the sign)

On the other hand, it appears to do something useful with current JDK implementation. Namely, sorting with such a comparator actually reverses the input. This happens, thanks to a particular implementation of TimSort algorithm used inside JDK.

You can try, for example, the following code and check the result. Experienced users may expect that it will fail with "Comparison method violates its general contract" when you have more data, but it's not!

That's because TimSort has a fast-path when your input is completely sorted in either direct or reverse way (which often happens in practice). In the latter case, it simply reverses the input and exits, so the sorting will actually take O(N).

What's important is that on the fast-path contract violation is not checked, so it will correctly process even huge array. Still, needless to say that nobody should do this. You can see above how IntelliJ IDEA yells at this code.

As comparator violates the contract, anything can happen. It works only by chance. It's possible that the next Java version will update the sorting algorithm, and it will stop working.

You can actually replace the algorithm with an older one using -Djava.util.Arrays.useLegacyMergeSort=true. This implementation is also 100% correct but it does not reverse the input in our case. Probably a good option to add to your test matrix?

In any case, don't misuse the comparators. If you need to reverse the stream, dump it into list, then call Collections.reverse. Probably soon we'll have 'reversed()' method that returns a view right in the List interface (see JEP 431 for details). openjdk.org/jeps/431

I will mention this case in Chapter 7 of my book "100 Java Mistakes". The part of the book is already available in @ManningBooks MEAP program. manning.com/books/100-java…

@tagir_valeev The comparator is at least transitive, isn't it? 😜😂 If it wasn't, then this can happen: github.com/mmirwaldt/Cybe… or github.com/mmirwaldt/Cybe…

@tagir_valeev There’s a simple fix: change -1 to 1. HTH LOL