Records in a stream: group, sort and summarise

Records plus streams cover most reporting work: a small immutable carrier and a declarative pipeline over it.

Code
record Sale(String rep, String region, int amount) {}
var sales = List.of(
        new Sale("Ava", "north", 500), new Sale("Ben", "north", 300),
        new Sale("Cara", "south", 900), new Sale("Ava", "south", 100));

Map<String, Integer> byRep = sales.stream().collect(
        Collectors.groupingBy(Sale::rep, TreeMap::new, Collectors.summingInt(Sale::amount)));
System.out.println("total by rep: " + byRep);

Optional<Sale> best = sales.stream().max(Comparator.comparingInt(Sale::amount));
System.out.println("largest sale: " + best.orElseThrow());
Output
total by rep: {Ava=600, Ben=300, Cara=900}
largest sale: Sale[rep=Cara, region=south, amount=900]
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