CKTIS / Java
Comparator.nullsFirst — put null values first
Use `Comparator.nullsFirst` to put missing ages before known ages among records that tie on the primary sort key.
Version: Java SE 21
Syntax
static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)Comparator.nullsFirst is a static method on java.util.Comparator, available since Java 8. It returns a Comparator<T> that orders null before any non-null value. Comparing two null values returns 0. The supplied comparator, which can compare values of type T or a supertype, is called only when both values are non-null.
Pass Comparator.naturalOrder() to use natural ordering for present values, such as ascending numeric order for ages. In Comparator.nullsFirst(null), the null argument means there is no comparator for present values: all non-null values compare as equal rather than being sorted in natural order.
When the key can be missing but the object is present, pass the key comparator as the second argument to thenComparing. In the example, Person::age returns an Integer, which can be null unlike int. Age is compared only when the group comparison returns 0. This setup does not handle a list element that is itself null: extracting its group would throw NullPointerException.
Examples
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Person(String group, String name, Integer age) {}
public static void main(String[] args) {
var people = new ArrayList<>(List.of(
new Person("B", "Ivo", null),
new Person("A", "Mia", 30),
new Person("A", "Ada", null),
new Person("A", "Leo", 21),
new Person("A", "Eli", null)
));
Comparator<Person> byGroupThenAge = Comparator.comparing(Person::group)
.thenComparing(Person::age,
Comparator.nullsFirst(Comparator.naturalOrder()));
people.sort(byGroupThenAge);
for (Person person : people) {
System.out.println(person.group() + " " + person.name() + " " + person.age());
}
}
}
Result
A Ada null A Eli null A Leo 21 A Mia 30 B Ivo null
In group A, Ada and Eli have `null` ages and keep their input order because `List.sort` is stable. Leo (21) and Mia (30) follow. Ivo belongs to group B, so he comes last despite his missing age.
Related lessons
- Java · Lesson 35 · Intermediate · Version: 2