Course contentsShow
← Java
Lesson 1348 of 2,87030. Comparable and ComparatorFree lesson

Using reversed() with Natural Ordering

Apply reversed() to Comparator.naturalOrder() to sort elements in descending order without writing custom logic.

Using reversed() with Natural Ordering

You'll learn how to instantly reverse natural ordering without writing any custom sorting logic.

The Core Idea

In the last lesson, you learned that reversed() flips any comparator. But what if you don't have a custom comparator—you just want to sort elements in reverse natural order (descending instead of ascending)? Java provides Comparator.naturalOrder(), which returns a comparator that uses the natural ordering defined by a class's Comparable implementation. Combine it with reversed(), and you get instant descending order.

Think of it like this: naturalOrder() is the "sort A-Z" button, and chaining .reversed() immediately turns it into the "sort Z-A" button.

The Pattern

List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));

// Natural order (A-Z)
names.sort(Comparator.naturalOrder());
// [Alice, Bob, Charlie]

// Reversed natural order (Z-A)
names.sort(Comparator.naturalOrder().reversed());
// [Charlie, Bob, Alice]

This works with any type that implements Comparable: Integer, String, LocalDate, or your own custom classes.

Why This Matters

Instead of writing Collections.reverseOrder() (which also works), or creating a custom comparator, this approach is fluent and composable. It fits perfectly into chains with thenComparing():

people.sort(
    Comparator.comparingInt(Person::getAge).reversed()
        .thenComparing(Person::getName)
);
// Oldest first, then alphabetically by name

Key Takeaway:
Use Comparator.naturalOrder().reversed() to sort elements in descending natural order instantly, without any custom logic or additional code.