Library contents

Java Collectors.groupingBy

Group records that share a key, then count or sum each group. A sales report can group events by region or successful orders by customer.

A simple example

Collectors.groupingBy

  1. Start with A, B, A
  2. Do this Count each key
  3. Result A has 2, B has 1
The second A increases the existing A count from one to two.

Syntax

Java syntax
Collectors.groupingBy(keyFunction, TreeMap::new, Collectors.counting())
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Count events by region in key order

A reporting system receives a sequence of events or product codes with repetitions. Aggregate the values according to the required grouping and order so the report keeps the distinction between items and occurrences.

From the programvar counts = List.of("west", "east", "east").stream()
First output lineeast=2
Main.java
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

class Main {
    public static void main(String[] args) throws Exception {
        var counts = List.of("west", "east", "east").stream()
                .collect(Collectors.groupingBy(s -> s, TreeMap::new, Collectors.counting()));
        counts.forEach((region, n) -> System.out.println(region + "=" + n));
        System.out.println(counts.getOrDefault("north", 0L));
    }
}
Output
east=2
west=1
0

Specifying a TreeMap makes the printed key order predictable. A region with no events has no entry, so getOrDefault supplies the count for a lookup.

Advertisements

Count north-door returns

A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?

GivenN · S · N · N | count N
Worked result3

Count ready print jobs

A print desk groups the current jobs by status. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?

Givenready · held · ready | count ready
Worked result2

What to watch for

Pick the map type deliberately when the printed order of groups matters.

Documentation for Collectors.groupingBy