Chain comparators to sort by a primary key and break ties with a secondary key.
record Emp(String dept, String name) {}
var emps = new ArrayList<>(List.of(
new Emp("Sales", "Zoe"), new Emp("Eng", "Ava"),
new Emp("Sales", "Ana")));
emps.sort(Comparator.comparing(Emp::dept).thenComparing(Emp::name));
emps.forEach(e -> System.out.println(e.dept() + " - " + e.name()));
Eng - Ava
Sales - Ana
Sales - Zoe
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-26