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

Combining nullsFirst() with Custom Comparators

Wrap custom comparators with nullsFirst() or nullsLast() to add null-handling to existing comparison logic.

Combining nullsFirst() with Custom Comparators

You'll learn how to add null-safe handling to your own custom comparison logic by wrapping comparators with nullsFirst() or nullsLast().

The Core Idea

Sometimes you've already built a custom Comparator for complex business logic, but you realize your data might contain null values. Rather than rewriting your entire comparator to handle nulls manually, Java lets you wrap your existing comparator with nullsFirst() or nullsLast(). This adds a protective null-handling layer on top of your logic.

Think of it like putting a filter on a water tap: the tap (your custom comparator) does its job, but the filter (null-handling wrapper) catches anything problematic before it gets through.

How It Works

The nullsFirst() and nullsLast() methods accept another Comparator as a parameter. When sorting, they check for nulls first, then delegate to your custom comparator for non-null values.

Syntax:

Comparator<Person> customComparator = (p1, p2) -> 
    p1.getAge() - p2.getAge();

Comparator<Person> nullSafeComparator = 
    Comparator.nullsFirst(customComparator);

Now nullSafeComparator treats any null Person objects as "smallest" (sorting them first), while using your age-based logic for actual Person instances.

Practical Pattern

You can chain this with factory methods too:

Comparator<Person> byName = Comparator.comparing(Person::getName);
Comparator<Person> nullSafeByName = Comparator.nullsLast(byName);

This sorts by name normally, but pushes any null Person objects to the end.

Key Takeaway:
Wrap any existing Comparator with nullsFirst() or nullsLast() to add null-safe behavior without rewriting your comparison logic—separation of concerns at its finest.