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

Chaining reversed() with Null Handling

Combine reversed(), nullsFirst(), and nullsLast() in chains to create complex null-aware reversed comparators.

Chaining reversed() with Null Handling

You'll learn how to combine reversed(), nullsFirst(), and nullsLast() in a single chain to create sophisticated comparators that handle nulls gracefully while sorting in reverse order.

The Core Idea

When you need a reversed sort that also handles null values, you can chain these methods together. The order matters: typically you apply nullsFirst() or nullsLast() to establish null positioning, then call reversed() to flip the entire ordering—or vice versa, depending on your desired outcome.

Think of it like stacking instructions: "Put nulls at the end, then reverse everything" gives a different result than "Reverse the order, then put nulls at the end."

How the Chaining Works

// Sort by age descending, nulls last
Comparator<Person> comp = Comparator
    .comparing(Person::getAge, Comparator.nullsLast(Comparator.naturalOrder()))
    .reversed();

// Alternative: nulls first in reversed order
Comparator<Person> comp2 = Comparator
    .comparing(Person::getAge, Comparator.nullsFirst(Comparator.naturalOrder()))
    .reversed();

// Complex chain: name ascending (nulls last), then age descending
Comparator<Person> comp3 = Comparator
    .comparing(Person::getName, Comparator.nullsLast(Comparator.naturalOrder()))
    .thenComparing(Person::getAge, Comparator.nullsFirst(Comparator.naturalOrder()))
    .reversed();

The key insight: nullsFirst() and nullsLast() wrap an underlying comparator, and reversed() flips the entire comparison logic. When you reverse a nullsLast() comparator, nulls move to the front—because you've reversed the "last" positioning.

Practical Pattern

For descending order with specific null placement, nest your null-handling inside the key extractor comparator, then optionally apply reversed() to the whole chain.

Key Takeaway: Chain reversed() with nullsFirst() or nullsLast() to build complex null-aware comparators; remember that reversed() flips both value ordering and null positioning of the entire comparator it's called on.