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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.