Streams: sorting on several keys with Comparator chaining

Comparator.comparing followed by thenComparing reads like an ORDER BY clause, and reversed() flips the whole chain built so far.

Code
record Player(String name, int score, int age) {}
var players = new ArrayList<>(List.of(
        new Player("Ava", 90, 31), new Player("Ben", 90, 24), new Player("Cara", 75, 28)));

players.sort(Comparator.comparingInt(Player::score).reversed()
        .thenComparing(Player::name));

players.forEach(p -> System.out.println(p.name() + " " + p.score()));
Output
Ava 90
Ben 90
Cara 75
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-30