Sub topic 9
Handling nulls with nullsFirst and nullsLast
This chapter assumes you can write a Comparator with a lambda or method reference, and that you know Comparator.comparing, thenComparing and reversed. It also assumes you know how List.sort works. The chapter explains why nulls break a comparison and how Comparator.nullsFirst and Comparator.nullsLast fix it. It also covers where the fix does not apply.
Why null breaks a comparison
Natural ordering calls compareTo on one element and passes the other as the argument. By convention, compareTo(null) throws NullPointerException. When a list contains null, the sort will sooner or later try to compare that element, and it fails.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class NullSortFails {
public static void main(String[] args) {
List<String> words = Arrays.asList("b", null, "a");
words.sort(Comparator.naturalOrder()); // throws NullPointerException
}
}Comparator.naturalOrder() calls compareTo internally, so it inherits the failure. A hand-written lambda such as (x, y) -> x.length() - y.length() fails the same way, because it dereferences a null.
Null can appear in two different places, and they need different fixes:
| Where the null is | Example | Fix |
|---|---|---|
| The element itself | `[Ana, null, Bo]` | Wrap the whole comparator in `nullsFirst` or `nullsLast` |
| A field used as the sort key | A `Contact` whose `email` is null | Wrap the key comparator you pass to `comparing` |
Mixing these two up is the most common mistake with this API, so the sections below treat them separately.
What nullsFirst and nullsLast do
Both methods take a comparator and return a new comparator. The new comparator decides about nulls itself and only calls your comparator when both values are non-null.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class NullsFirstLast {
public static void main(String[] args) {
List<String> first = Arrays.asList("b", null, "a");
first.sort(Comparator.nullsFirst(Comparator.<String>naturalOrder()));
System.out.println(first); // [null, a, b]
List<String> last = Arrays.asList("b", null, "a");
last.sort(Comparator.nullsLast(Comparator.<String>naturalOrder()));
System.out.println(last); // [a, b, null]
}
}The rules for nullsFirst(cmp) are:
- If both arguments are null, they are equal (result 0).
- If only the first is null, it is smaller (negative result).
- If only the second is null, the first is larger (positive result).
- Otherwise the result is
cmp.compare(a, b).
nullsLast is the same with the sign flipped in rules 2 and 3. Because rule 1 returns 0 for two nulls, several nulls end up next to each other. Their relative order is whatever the stable sort preserves.
The wrapped comparator never sees a null, so it can be a plain naturalOrder() or a lambda that dereferences its arguments freely.
The null argument to nullsFirst
The wrapped comparator may itself be null. The documented meaning is that all non-null values are treated as equal. Only the nulls are moved.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class NullsOnly {
public static void main(String[] args) {
List<String> words = Arrays.asList("pear", null, "apple", "fig");
words.sort(Comparator.nullsLast(null));
System.out.println(words); // [pear, apple, fig, null]
}
}This partitions the list into non-null and null items. List.sort is stable, so the non-null items keep their original relative order. It is useful as a final step after another sort key, or when you only need the nulls out of the way.
Null fields inside objects
Most real data has null fields, not null elements. Suppose some contacts have no email address.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ContactSort {
record Contact(String name, String email) {}
public static void main(String[] args) {
List<Contact> contacts = new ArrayList<>(List.of(
new Contact("Di", null),
new Contact("Cy", "[email protected]"),
new Contact("Bo", null),
new Contact("Ana", "[email protected]")));
Comparator<Contact> byEmailThenName =
Comparator.comparing(Contact::email,
Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(Contact::name);
contacts.sort(byEmailThenName);
contacts.forEach(c -> System.out.println(c.name() + " " + c.email()));
// Ana [email protected]
// Cy [email protected]
// Bo null
// Di null
}
}The two-argument comparing(keyExtractor, keyComparator) extracts the key, then compares the two keys with the comparator you give it. The null check therefore runs on the key, which is what you want here. The records need Java 16 or later. With an ordinary class the comparator code is identical.
The thenComparing(Contact::name) step breaks the tie between Bo and Di, whose emails are both null. Without it, the two nulls compare as equal and keep their input order.
Compare this with the version that looks reasonable but fails:
Comparator<Contact> broken = Comparator.comparing(Contact::email); // NPE when an email is nullcomparing(Contact::email) calls compareTo on the extracted emails. As soon as one email is null, you get a NullPointerException. Wrapping the entire comparator would not help either:
// Only protects against a null Contact, not a null email.
Comparator<Contact> stillBroken = Comparator.nullsLast(Comparator.comparing(Contact::email));Here nullsLast guards the Contact objects, but the inner comparing still receives non-null contacts with null emails and throws.
If both problems exist (null contacts and null emails), nest the two wrappers:
Comparator<Contact> safe = Comparator.nullsLast(
Comparator.comparing(Contact::email,
Comparator.nullsLast(Comparator.naturalOrder())));Nullable numbers and comparingInt
comparingInt, comparingLong and comparingDouble take a function that returns a primitive. If your getter returns Integer and the value is null, the unboxing throws NullPointerException before any comparison happens. The null wrapper has no chance to help.
For a nullable Integer field, use comparing with a key comparator instead:
import java.util.Comparator;
public class NullableAge {
record Member(String name, Integer age) {}
static final Comparator<Member> BY_AGE_NULLS_LAST =
Comparator.comparing(Member::age,
Comparator.nullsLast(Comparator.<Integer>naturalOrder()));
}This costs a little boxing, which rarely matters. Use comparingInt only when the value can never be null.
Combining nulls with reversed
reversed() flips the entire comparator, including its null placement. A comparator that puts nulls first becomes one that puts them last.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ReverseNulls {
static List<String> sorted(Comparator<String> cmp) {
List<String> list = Arrays.asList("b", null, "a");
list.sort(cmp);
return list;
}
public static void main(String[] args) {
System.out.println(sorted(Comparator.nullsFirst(Comparator.<String>naturalOrder())));
// [null, a, b]
System.out.println(sorted(Comparator.nullsFirst(Comparator.<String>naturalOrder()).reversed()));
// [b, a, null]
System.out.println(sorted(Comparator.nullsFirst(Comparator.<String>reverseOrder())));
// [null, b, a]
System.out.println(sorted(Comparator.nullsLast(Comparator.<String>reverseOrder())));
// [b, a, null]
}
}The second and third lines show the difference. Calling reversed() on the outside reverses nulls and values together. Putting reverseOrder() on the inside reverses only the non-null values and leaves the null rule alone. To get "descending, with nulls at the end", put the reversal inside:
Comparator.nullsLast(Comparator.<String>reverseOrder())With a key extractor, the same idea applies to the key comparator:
Comparator.comparing(Contact::email,
Comparator.nullsLast(Comparator.<String>reverseOrder()))Streams, arrays and sorted collections
The same comparator works anywhere a Comparator is accepted.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class NullsEverywhere {
public static void main(String[] args) {
Comparator<String> nullsLastNatural =
Comparator.nullsLast(Comparator.<String>naturalOrder());
List<String> fromStream = Arrays.asList("b", null, "a").stream()
.sorted(nullsLastNatural)
.collect(Collectors.toList());
System.out.println(fromStream); // [a, b, null]
String[] array = {"b", null, "a"};
Arrays.sort(array, nullsLastNatural);
System.out.println(Arrays.toString(array)); // [a, b, null]
TreeSet<String> set = new TreeSet<>(nullsLastNatural);
set.add("b");
set.add(null);
set.add("a");
System.out.println(set); // [a, b, null]
}
}A TreeSet or TreeMap built with no comparator uses natural ordering and throws on a null element or key. Built with a null-tolerant comparator, it accepts null. That is the only way to store a null in these collections.
PriorityQueue is different. It rejects null elements in offer and add regardless of the comparator, so there is nothing to wrap. Filter the nulls out first, or store a wrapper object.
Choosing where to deal with null
| Situation | Approach |
|---|---|
| Null should be impossible | Leave it. A `NullPointerException` points to a bug in your data. |
| A few elements may be null | `nullsFirst` or `nullsLast` around the whole comparator |
| A field may be null | `comparing(getter, nullsFirst(...))` or `nullsLast(...)` on the key |
| Nullable `Integer` or `Double` field | `comparing` with a null-safe key comparator, not `comparingInt` |
| Nulls must be dropped | Filter them before sorting, for example with `Objects::nonNull` |
Do not put null handling inside compareTo. A natural ordering should state clearly that nulls are not allowed, and nulls are better handled at each call site, where the right placement is known.
Exercise
Given List<String> names = Arrays.asList("Zed", null, "amy", "Bob");, write a comparator that sorts names in descending case-insensitive order and puts the null at the end. What is the resulting list?
Show answer
Use Comparator.nullsLast(Comparator.<String>reverseOrder()) for plain descending, but for case-insensitive order use Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER.reversed()). Sorting with it gives [Zed, Bob, amy, null]. The reversal sits inside nullsLast, so only the non-null names are reversed and the null stays last. Writing .reversed() after nullsLast(...) would move the null to the front.
Exercise
A Task has a nullable LocalDate dueDate and a non-null String title. Write a comparator that orders tasks by due date, earliest first, with undated tasks last, and breaks ties by title. Why is Comparator.comparing(Task::dueDate) not enough?
Show answer
Comparator<Task> c = Comparator.comparing(Task::dueDate, Comparator.nullsLast(Comparator.<LocalDate>naturalOrder())).thenComparing(Task::title);. Comparator.comparing(Task::dueDate) calls compareTo on the extracted dates, so a task with a null dueDate causes a NullPointerException. The key comparator passed as the second argument handles the null key, and thenComparing(Task::title) orders the undated tasks among themselves.