Sub topic 9
Handling nulls with nullsFirst and nullsLast
Why null needs a policy
This chapter assumes you know Java classes, generics, the Collections framework, lambda expressions, method references, and the equals and hashCode methods.
A comparator must decide the order of every pair of values that it receives. Natural ordering usually cannot compare null with a real value. For example, "a".compareTo(null) throws a NullPointerException.
The Comparator class provides two wrappers for an explicit policy:
Comparator.nullsFirst(comparator)putsnullbefore every non-null value.Comparator.nullsLast(comparator)putsnullafter every non-null value.
The wrapped comparator still decides the order among non-null values.
Handling null elements
Suppose a list contains strings and one missing value:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class NullElementsExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("b", null, "a");
words.sort(Comparator.nullsFirst(
Comparator.<String>naturalOrder()));
System.out.println(words); // [null, a, b]
words.sort(Comparator.nullsLast(
Comparator.<String>naturalOrder()));
System.out.println(words); // [a, b, null]
}
}Comparator.naturalOrder() compares strings using their natural ordering. The nullsFirst and nullsLast wrappers add the missing-value rule.
The wrapper returns zero when both values are null. It delegates to the inner comparator when both values are non-null.
Handling null fields
A different problem occurs when the objects are non-null but a field used as a sort key is null. Build a comparator for the key, then pass it to Comparator.comparing.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class NullFieldExample {
static class Person {
private final String name;
Person(String name) {
this.name = name;
}
String getName() {
return name;
}
@Override
public String toString() {
return String.valueOf(name);
}
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Bo"));
people.add(new Person(null));
people.add(null);
people.add(new Person("Ana"));
Comparator<String> namesLast =
Comparator.nullsLast(Comparator.<String>naturalOrder());
Comparator<Person> byName =
Comparator.comparing(Person::getName, namesLast);
people.sort(Comparator.nullsFirst(byName));
System.out.println(people); // [null, Ana, Bo, null]
}
}There are two policies in this example:
namesLastputs a person with a null name after people with names.- The outer
nullsFirstputs a nullPersonbefore every person.
Without the outer wrapper, byName would try to call getName on a null Person. Without the key comparator, the null name would cause a failure inside the name comparison.
| Situation | Comparator to use |
|---|---|
| Null list elements | `Comparator.nullsFirst(...)` or `nullsLast(...)` |
| Null sort keys | Pass a null-aware comparator to `Comparator.comparing(...)` |
Choosing a policy
Choose nullsFirst when null means “unknown,” “not supplied,” or “needs attention” and should appear at the beginning. Choose nullsLast when real values should appear first, which is common in user-facing lists.
A null policy should be documented because it is part of the ordering's meaning. Also apply the same policy consistently wherever the comparator is reused, such as sorting, a TreeSet, or a PriorityQueue.
Exercise
What happens when Comparator.nullsLast(Comparator.naturalOrder()) compares two non-null strings?
Show answer
It delegates the comparison to the wrapped natural-order comparator. The wrapper only changes how null values are ordered.