Reverse a comparator in Java 8
You can use Comparator.reverseOrder()
to have a comparator giving the reverse of the natural ordering.
If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed()
.
Sample code:
Stream.of(1, 4, 2, 5)
.sorted(Comparator.reverseOrder());
// stream is now [5, 4, 2, 1]
Stream.of("foo", "test", "a")
.sorted(Comparator.comparingInt(String::length).reversed());
// stream is now [test, foo, a], sorted by descending length
You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:
Comparator<SomeEntity> ENTITY_COMPARATOR =
Comparator.comparing(SomeEntity::getProperty1, Comparator.reverseOrder())
.thenComparingInt(SomeEntity::getProperty2)
.thenComparing(SomeEntity::getProperty3, Comparator.reverseOrder());
Java 8 Comparator
interface has a reversed
method : https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reversed--