The nullsLast() Method: Null-Safe Comparisons
What you'll learn: How to use Comparator.nullsLast() to safely handle null values by automatically placing them at the end of your sorted collection.
The Problem with Nulls
When sorting collections that might contain null elements, calling compare() on a regular Comparator will throw a NullPointerException. This is problematic in real-world scenarios where missing data is common—perhaps user records with optional fields, or database results with nullable columns.
What nullsLast() Does
Comparator.nullsLast() wraps any existing comparator to make it null-safe. It ensures that:
- Null values are sorted after all non-null values
- Non-null values are compared using your wrapped comparator
- Multiple nulls are considered equal
Think of it as a safety wrapper: it catches nulls before they reach your actual comparison logic and automatically pushes them to the end of the line.
The Syntax
Comparator<T> nullSafeComparator =
Comparator.nullsLast(yourComparator);
Typical Usage Pattern
List<String> names = Arrays.asList("Alice", null, "Charlie", null, "Bob");
// Natural order, but nulls go last
Comparator<String> safeComparator =
Comparator.nullsLast(Comparator.naturalOrder());
Collections.sort(names, safeComparator);
// Result: [Alice, Bob, Charlie, null, null]
You can also chain it with other comparator methods:
Comparator<Person> byAge =
Comparator.nullsLast(Comparator.comparing(Person::getAge));
Key Takeaway: Use Comparator.nullsLast() to wrap any comparator when your collection might contain nulls and you want those nulls sorted to the end—preventing NullPointerException while maintaining predictable sort order.