Explain Codes LogoExplain Codes Logo

Reverse a Comparator in Java 8

java
stream-api
comparator
sorting
Anton ShumikhinbyAnton Shumikhin·Mar 5, 2025
TLDR

Reverse the sorting order in a snap with Comparator.reversed().

Comparator<String> reversed = Comparator.<String>naturalOrder().reversed();

That’s it! Strings sort in reverse alphabetical order — 

no additional steps needed.

The Stream API: Simplified descending sorting

Java 8 lends an upper hand with Streams and Comparator — welcome to simplified descending sorting.

List<String> words = Arrays.asList("B", "A", "C"); List<String> sortedDescending = words.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); // Because who doesn't love reverse alphabets?

Hope you dislike alphabets 'cause now they're backwards.

Complex types: Meet Comparator chaining

Chaining Comparators — for when basic sorting just doesn't sort it.

List<Person> people = getPeople(); Comparator<Person> byAgeThenName = Comparator .comparing(Person::getAge) .reversed() .thenComparing(Person::getName); // Old before young, but alphabetically. Seems fair? Collections.sort(people, byAgeThenName);

We've sorted people by age (oldest first), and then by name. Take that, youth! 👴

Customizing sort direction

Ascending, descending. It's all about the perspective.

int order = -1; // 1 for ascending, -1 for descending Collections.sort(people, (p1, p2) -> order * p1.getAge().compareTo(p2.getAge())); // Reverse the age? Now that's a potion we'd drink!

Setting order to 1 or -1 flips the sorting order. Choose your perspective.

Tackling complex data types

Sorting your way through complex types with ease and style.

Comparator<CustomType> customComparator = Comparator.comparing(CustomType::getCustomField).reversed(); // More complex than playing Tetris blindfolded. Collections.sort(listOfComplexType, customComparator);

Using .reversed(), we're sort wizards now.

Rain on complex sorts with multi-property

When your data is multi-attributed like your personality traits, bring in thenComparing.

// Sorting by age in ascending then by name in descending Comparator<Person> complexComparator = Comparator .comparing(Person::getAge) .thenComparing(Comparator.comparing(Person::getName).reversed()); people.sort(complexComparator); // It's an age-before-beauty-type thing (in reverse).

We're now rocking tiered sorting: by age (youngest first) then by name in reverse.

Runtime sorting adjustments with Conditionals

Dynamic sort at runtime? We've got your back!

boolean reverseName = someCondition; Comparator<Person> conditionalComparator = Comparator .comparing(Person::getAge) .thenComparing( person -> person.getName(), reverseName ? Comparator.reverseOrder() : Comparator.naturalOrder() ); Collections.sort(people, conditionalComparator);

The name order adjusts according to the bool reverseName. Sorting, meet flexibility.