Comparator on record accessors sorts declaratively

Method references to record accessors keep sorting logic readable, and Comparator.comparing composes several keys without a custom class.

Code
record Topic(String title, String category, int views) {}
var topics = new ArrayList<>(List.of(
        new Topic("Streams", "java", 900),
        new Topic("Maps", "java", 900),
        new Topic("Indexes", "sql", 400)));

topics.sort(Comparator.comparing(Topic::category)
        .thenComparing(Comparator.comparingInt(Topic::views).reversed())
        .thenComparing(Topic::title));

topics.forEach(t -> System.out.println(t.category() + " | " + t.views() + " | " + t.title()));
Output
java | 900 | Maps
java | 900 | Streams
sql | 400 | Indexes
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