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

Chaining reversed() with comparing()

Combine reversed() with comparing() factory methods to reverse specific field-based comparisons in a fluent chain.

Chaining reversed() with comparing()

You'll learn how to reverse specific field comparisons by combining reversed() with comparing() factory methods.

The Core Idea

You've already seen how reversed() flips the entire comparison order, and how comparing() creates comparators based on specific fields. Now you can combine them in a single chain to reverse just one criterion while keeping others in normal order.

The key insight: Comparator.comparing() returns a Comparator, and every Comparator has a reversed() method. You can call reversed() right after comparing() to flip that specific field's comparison before chaining additional criteria with thenComparing().

How It Works

The pattern looks like this:

Comparator.comparing(Person::getAge).reversed()

This creates a comparator that sorts by age in descending order (oldest first).

You can then chain more criteria:

Comparator.comparing(Person::getAge).reversed()
          .thenComparing(Person::getName)

This sorts by age descending, then by name ascending (for people with the same age).

Fluent Control Over Each Level

Think of it like building a custom sorting recipe: "First, newest to oldest by date. Then, A to Z by title." Each step gets its own direction.

Comparator.comparing(Book::getPublicationYear).reversed()
          .thenComparing(Book::getTitle)
          .thenComparingInt(Book::getPageCount)

Here: newest books first, alphabetically by title within the same year, then shortest to longest.

Key Takeaway:
Use .reversed() immediately after comparing() to reverse only that specific field's sort order, then chain additional criteria with thenComparing() for fine-grained, multi-level sorting control.