The nullsFirst() Method: Null-Safe Comparisons
You'll learn how to handle null values gracefully in sorting operations using Comparator.nullsFirst().
The Problem with Nulls
When sorting collections, encountering null values can cause NullPointerException errors. If your data might contain nulls, you need a way to tell the sorting algorithm where to place them—without writing defensive null-checking code everywhere.
What Is nullsFirst()?
Comparator.nullsFirst() is a static factory method that wraps an existing comparator to treat null values as smaller than any non-null value. This means nulls will always appear first in the sorted order.
The method signature looks like this:
static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)
How It Works
Think of nullsFirst() as a protective wrapper around your comparator. It intercepts comparisons and handles three cases:
- Both null: returns 0 (equal)
- First null: returns -1 (first is smaller)
- Neither null: delegates to the wrapped comparator
Example
List<String> names = Arrays.asList("Charlie", null, "Alice", null, "Bob");
Comparator<String> safeComparator = Comparator.nullsFirst(Comparator.naturalOrder());
Collections.sort(names, safeComparator);
// Result: [null, null, Alice, Bob, Charlie]
You can chain it with other comparator methods:
Comparator<Person> byAge = Comparator.nullsFirst(
Comparator.comparingInt(Person::getAge)
);
Key Takeaway: Use Comparator.nullsFirst() to wrap any comparator when your data may contain null values, ensuring they sort to the beginning without throwing exceptions.