Streams: groupingBy's map-factory overload chooses the result map type

The three-argument groupingBy overload takes a Supplier for the map itself, so grouping can land straight in a TreeMap and come out already sorted by key, with no separate sort step.

Code
record Player(String name, String team) {}
List<Player> players = List.of(
        new Player("Amy", "Red"), new Player("Bo", "Blue"), new Player("Cid", "Red"));
Map<String, List<String>> byTeam = players.stream()
        .collect(Collectors.groupingBy(Player::team, TreeMap::new,
                Collectors.mapping(Player::name, Collectors.toList())));
System.out.println("Grouped in a TreeMap (sorted by team): " + byTeam);
Output
Grouped in a TreeMap (sorted by team): {Blue=[Bo], Red=[Amy, Cid]}
Advertisement
More in JAVA

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-09-27

© Java Coding Hub · About · Contact · Privacy · Terms