Stop 09 · Lambdas & StreamsTopics · 5/7

Collectors & groupingBy

Part of the Java Roadmap

In short

Most reports are 'something per something': sales per city, students per grade, orders per day. Collectors.groupingBy answers those in one statement, like GROUP BY in SQL.

Collectors turn stream results into collections and summaries: toList, toSet, toMap, joining, counting and groupingBy for grouping items by a key.

The jaadu sorts a heap of envelopes into a wooden rack of pigeonholes at a busy post office counter.

Think of it like this

The post office sorting rack

At a post office, a clerk picks up each letter, reads the PIN code and drops it into the matching pigeonhole. At the end, each hole holds a pile, and you can count or weigh each pile. groupingBy is the clerk, the key function reads the PIN code, and the downstream collector counts or weighs.

Watch it happen

Four sales grouped by city

Pune·Tea 200
0
Pune·Coffee 300
1
Delhi·Tea 150
2
Delhi·Tea 400
3

1/4Four Sale records, each with a city, a product and an amount.

The big ideas

What you need to know

The everyday collectors

toList(), toSet(), toMap(), joining(", ") and counting() cover most needs. Stream.toList() is a handy shortcut since Java 16.

groupingBy(key)

Returns Map<Key, List<T>>. Each map entry holds all elements that share that key.

Downstream collectors

groupingBy(key, counting()), summingInt, averagingDouble or mapping(...) turn each group's list into a summary.

Choose the map type

The default HashMap has no order. Pass TreeMap::new as the second argument for keys in sorted order.

See it in code

Walk through the code

java
1import java.util.List;2import java.util.Map;3import java.util.TreeMap;4import java.util.stream.Collectors;5 6public class GroupingDemo {7    record Sale(String city, String product, int amount) {}8 9    public static void main(String[] args) {10        List<Sale> sales = List.of(11            new Sale("Pune", "Tea", 200),12            new Sale("Pune", "Coffee", 300),13            new Sale("Delhi", "Tea", 150),14            new Sale("Delhi", "Tea", 400)15        );16 17        Map<String, List<Sale>> byCity = sales.stream()18                .collect(Collectors.groupingBy(Sale::city));19 20        Map<String, Integer> totalByCity = sales.stream()21                .collect(Collectors.groupingBy(Sale::city, TreeMap::new,22                         Collectors.summingInt(Sale::amount)));23 24        Map<String, Long> countByProduct = sales.stream()25                .collect(Collectors.groupingBy(Sale::product, Collectors.counting()));26 27        String cities = sales.stream().map(Sale::city).distinct()28                .collect(Collectors.joining(", "));29 30        System.out.println(totalByCity);  // {Delhi=550, Pune=500}31        System.out.println(cities);       // Pune, Delhi32    }33}

1/4Plain groupingBy: each city maps to the list of its Sale records.

Grouping, summing, counting and joining over a small list of tea shop sales.

Save yourself the pain

Common mistakes

Oops

Collectors.toMap(Sale::city, Sale::amount) when cities repeat.

Do this instead

Duplicate keys throw IllegalStateException. Add a merge function: toMap(Sale::city, Sale::amount, Integer::sum), or use groupingBy.

Oops

Expecting groupingBy results to print in insertion or alphabetical order.

Do this instead

The default is a HashMap with no order. Use TreeMap::new for sorted keys or LinkedHashMap::new for insertion order.

Oops

Adding to the list returned by stream.toList().

Do this instead

It is unmodifiable. Use collect(Collectors.toCollection(ArrayList::new)) if you need to change it later.

Your mission

Class result summary

~30 min

Quick check

What type does sales.stream().collect(Collectors.groupingBy(Sale::city, Collectors.counting())) return?

Go deeper

  1. 1Group a list of students by grade with Collectors.groupingBy().
  2. 2Count items per category using groupingBy with counting().
  3. 3Join a list of names into a comma-separated string with joining().

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge