Handling Nulls in Natural Ordering
You'll learn how to safely sort collections with nulls using their natural order by combining nullsFirst() or nullsLast() with Comparator.naturalOrder().
The Problem with Nulls and Natural Ordering
When you have a collection of naturally comparable objects (like String, Integer, or custom classes implementing Comparable), you might want to sort them using their natural order. But what if the collection contains null values? Calling compareTo() on a null will throw a NullPointerException, crashing your sort.
The Solution: Null-Safe Natural Ordering
Java provides a clean way to handle this by wrapping Comparator.naturalOrder() with null-handling methods:
// Nulls come first, then natural order
Comparator<String> nullsFirstNatural =
Comparator.nullsFirst(Comparator.naturalOrder());
// Nulls come last, then natural order
Comparator<String> nullsLastNatural =
Comparator.nullsLast(Comparator.naturalOrder());
Think of it like organizing books on a shelf: you decide whether books without titles (nulls) go at the beginning or end, while titled books are alphabetized in between.
Practical Example
List<Integer> numbers = Arrays.asList(5, null, 2, null, 8, 1);
// Sort with nulls first
numbers.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
// Result: [null, null, 1, 2, 5, 8]
// Sort with nulls last
numbers.sort(Comparator.nullsLast(Comparator.naturalOrder()));
// Result: [1, 2, 5, 8, null, null]
This pattern works with any type that has natural ordering: String, all primitive wrappers, dates, and your own Comparable classes.
Key Takeaway: Wrap Comparator.naturalOrder() with nullsFirst() or nullsLast() to create null-safe comparators that sort using natural ordering while gracefully handling null elements without crashes.