Comparator nullsFirst And nullsLast

Sort records whose keys may be null by wrapping inner comparators with nullsFirst or nullsLast, keeping null handling out of business code.

JavaData Integrity

Code

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

record Employee(String name, String team, Integer level) {}

public class Main {
    public static void main(String[] args) {
        List<Employee> staff = new ArrayList<>(List.of(
            new Employee("ada", "core", 5),
            new Employee("bob", null, 3),
            new Employee("cy", "core", null),
            new Employee("dee", "web", 4)
        ));

        // nullsLast:为 null 的键排在最后,比较器内部不再抛 NPE
        Comparator<Employee> byTeam = Comparator.comparing(
            Employee::team, Comparator.nullsLast(Comparator.<String>naturalOrder()));
        staff.sort(byTeam);
        staff.forEach(e -> System.out.println("team=" + e.team() + " name=" + e.name()));

        // nullsFirst + reverseOrder:null 在前,其余等级从高到低
        Comparator<Employee> byLevel = Comparator.comparing(
            Employee::level, Comparator.nullsFirst(Comparator.<Integer>reverseOrder()));
        staff.sort(byLevel);
        staff.forEach(e -> System.out.println("level=" + e.level() + " name=" + e.name()));
    }
}

What the code does

Comparator nullsFirst And nullsLast keeps everything in the classes Employee and Main and the function main.

Applying it

Running the file prints labeled results such as team=, level= — each operation’s effect is visible in the output.

Statements that matter

staff.sort(byLevel);
staff.sort(byTeam);

Interactive Tools for This Topic

FAQ

What does Comparator nullsFirst And nullsLast print when run?
Invoke the file as-is — the `team=`, `level=` prefixes identify which step printed each line.