Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparator.nullsLast: put null values last

Place `null` after all non-null values for a given sort key, such as when ordering people by last name and then by first name.

Version: Java SE 21

Syntax

static <T> Comparator<T> nullsLast(Comparator<? super T> comparator)

Comparator.nullsLast is a static method on java.util.Comparator, available since Java 8. It returns a comparator that ranks null after every non-null value. Comparing two null values returns 0. The supplied comparator is used only when both values are non-null.

In Comparator.nullsLast(null), the null argument means there is no comparator for non-null values, so they all tie. To keep their natural order, pass Comparator.naturalOrder(). An empty string "" is not null.

If the objects themselves are non-null but their keys can be null, pass the key comparator to Comparator.comparing and, for a second key, to thenComparing. The second key breaks ties only when the first comparison returns 0, including when both last names are null. If a list element can itself be null, wrap the whole object comparator as well so that no key extractor is called on that element.

To reverse the natural order of non-null values while keeping null last, use Comparator.nullsLast(Comparator.reverseOrder()). Calling reversed() on the finished comparator flips the entire order and moves null to the front.

Examples

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    record Person(String lastName, String firstName) {}

    public static void main(String[] args) {
        var people = new ArrayList<>(List.of(
                new Person(null, "Zoe"),
                new Person("Lee", null),
                new Person("Lee", "Mia"),
                new Person("Adams", null),
                new Person("Lee", "Ava")
        ));

        Comparator<String> nameOrder = Comparator.nullsLast(Comparator.naturalOrder());
        Comparator<Person> personOrder = Comparator
                .comparing(Person::lastName, nameOrder)
                .thenComparing(Person::firstName, nameOrder);

        people.sort(personOrder);
        for (Person person : people) {
            System.out.println(person.lastName() + ", " + person.firstName());
        }
    }
}

Result

Adams, null
Lee, Ava
Lee, Mia
Lee, null
null, Zoe

`Adams, null` comes before every `Lee` entry because the last name is compared first. Within the `Lee` group, the missing first name comes last, and the person with no last name comes after everyone who has one.

Related lessons

  • Java · Lesson 35 · Intermediate · Version: 2

Sources