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

Reversing a Comparator with reversed()

Learn how Comparator.reversed() creates a new comparator that inverts the ordering of an existing comparator.

Reversing a Comparator with reversed()

You'll learn how to flip the sort order of any existing comparator using the reversed() method.

Sometimes you've built a perfect comparator—maybe using comparing() or thenComparing()—but you need the exact opposite sort order. Instead of rewriting the logic, Java provides the reversed() method that creates a new comparator inverting the original's ordering.

The Core Idea

Think of reversed() as flipping a sorting rule upside down. If your comparator sorts students by GPA from lowest to highest, calling reversed() on it instantly gives you a comparator that sorts from highest to lowest. It's mathematically equivalent to multiplying all your comparison results by -1.

The method is defined on the Comparator interface itself, so any comparator—whether built with factory methods, lambdas, or anonymous classes—can be reversed.

How It Works

Comparator<Person> byAge = Comparator.comparingInt(Person::getAge);
Comparator<Person> byAgeDescending = byAge.reversed();

// Sort youngest to oldest with byAge
// Sort oldest to youngest with byAgeDescending

You can also chain reversed() directly:

Comparator<Person> oldestFirst = 
    Comparator.comparingInt(Person::getAge).reversed();

This works beautifully with complex chains too:

Comparator<Student> byGPAThenName = 
    Comparator.comparingDouble(Student::getGPA)
              .reversed()  // highest GPA first
              .thenComparing(Student::getName);  // then alphabetically

Notice that reversed() only affects the comparator before it in the chain—not the thenComparing() that follows.

Key Takeaway:
Use reversed() to invert any comparator's ordering without rewriting logic; it returns a new comparator where positive becomes negative and vice versa.