Java 8: Multi-field sort with Comparator.thenComparing

Chain comparators to sort by a primary key and break ties with a secondary key.

Code
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()));
Output
Eng - Ava
Sales - Ana
Sales - Zoe
Advertisement

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