Comparator Chaining Multi Field Sort
Build a multi-field sort with Comparator.comparing thenComparing and nullsLast so secondary and tertiary orderings stay declarative.
Code
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class MultiFieldSort {
record Employee(String department, String lastName, Integer salary) {}
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("eng", "Nguyen", 120_000),
new Employee("eng", "Adler", 105_000),
new Employee("eng", "Adler", 99_000),
new Employee("ops", "Costa", 88_000),
new Employee("ops", null, 91_000)));
Comparator<Employee> byDepartment = Comparator.comparing(Employee::department);
Comparator<Employee> byLastName =
Comparator.comparing(Employee::lastName, Comparator.nullsLast(Comparator.naturalOrder()));
Comparator<Employee> bySalaryDesc = Comparator.comparingInt(Employee::salary).reversed();
staff.sort(byDepartment.thenComparing(byLastName).thenComparing(bySalaryDesc));
staff.forEach(e ->
System.out.printf("%s %-8s %d%n", e.department(), e.lastName() == null ? "(n/a)" : e.lastName(), e.salary()));
}
}Inside the snippet
Count the classes MultiFieldSort and Employee and the function main as the entire surface area of Comparator Chaining Multi Field Sort.
Key statements
staff.sort(byDepartment.thenComparing(byLastName).thenComparing(bySalaryDesc));
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.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
- How do you run Comparator Chaining Multi Field Sort?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.