Stream groupingBy

Collectors.groupingBy turns a stream into a map from a key to the elements that share it, and a downstream collector decides what each group becomes: a list, a count, a total, a maximum or another map. This page explains how groupingBy works, runs the common downstream collectors and the newer filtering, flatMapping and teeing, and shows the traps with null keys, Optional results and result types.

Contents

How groupingBy works

Collectors.groupingBy, added in Java 8, takes a classifier function that computes a key for each element. As the stream runs, it keeps a map from each key to a container for that group, creating the container the first time a key appears and adding each element to it. At the end, every group is finished by the downstream collector: by default toList(), but any collector works, including another groupingBy.

It has three forms. groupingBy(classifier) gives Map<K, List<T>>. groupingBy(classifier, downstream) changes what each group becomes. groupingBy(classifier, mapFactory, downstream) also chooses the map type, such as TreeMap::new for sorted keys. Only keys that occur appear in the map; there are no empty groups.

Common downstream collectors
CollectorSinceEach group becomes
toList(), toSet(), toCollection(...)Java 8A collection of the elements
counting()Java 8A Long count
summingInt, averagingDouble, summarizingDoubleJava 8A total, an average, or all statistics
mapping(f, downstream)Java 8The downstream result of f applied to each element
maxBy, minByJava 8An Optional of the largest or smallest
collectingAndThen(c, finisher)Java 8The result of c, transformed
filtering, flatMappingJava 9Only matching elements, or flattened ones
teeing(c1, c2, merger)Java 12Two results combined (also usable without grouping)

The examples use a shared Sale record and ran on JDK 21. Building a map with unique keys instead is covered on converting a list to a map.

Basic grouping: lists, counts and totals

The sample data is six sales across three regions and three products, so both groupings by region and by product have groups of different sizes.

Java
import java.util.List;

// Shared sample data for the examples on this page
public record Sale(String region, String product, int units, double price) {

    public double revenue() {
        return units * price;
    }

    public static List<Sale> sample() {
        return List.of(
                new Sale("north", "laptop", 3, 900.0),
                new Sale("south", "phone", 10, 400.0),
                new Sale("north", "phone", 4, 400.0),
                new Sale("east", "laptop", 1, 950.0),
                new Sale("south", "laptop", 2, 900.0),
                new Sale("north", "tablet", 6, 300.0));
    }
}
Java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class BasicGrouping {

    public static void main(String[] args) {
        List<Sale> sales = Sale.sample();

        // Default: Map<key, List<element>>
        Map<String, List<Sale>> byRegion = sales.stream()
                .collect(Collectors.groupingBy(Sale::region));
        System.out.println("north has " + byRegion.get("north").size() + " sales");

        // Downstream collector: count per group (TreeMap for sorted keys)
        Map<String, Long> countByRegion = sales.stream()
                .collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                        Collectors.counting()));
        System.out.println("count:    " + countByRegion);

        // Sum per group
        Map<String, Integer> unitsByProduct = sales.stream()
                .collect(Collectors.groupingBy(Sale::product, TreeMap::new,
                        Collectors.summingInt(Sale::units)));
        System.out.println("units:    " + unitsByProduct);

        // Keep only one field of each element
        Map<String, List<String>> productsByRegion = sales.stream()
                .collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                        Collectors.mapping(Sale::product, Collectors.toList())));
        System.out.println("products: " + productsByRegion);
    }
}

Output:

Output
north has 3 sales
count:    {east=1, north=3, south=2}
units:    {laptop=6, phone=14, tablet=6}
products: {east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]}
  • groupingBy(Sale::region) gave a list of sales per region; north has 3.
  • counting() replaced each list by its size, and summingInt(Sale::units) by the total units per product.
  • mapping(Sale::product, toList()) kept only the product names in each group.
  • TreeMap::new as the map factory sorts the keys, which makes reports readable and output stable. The default HashMap order is arbitrary.

Averages, maximums, nesting and partitions

The same sales are grouped with richer downstream collectors, the kind used for dashboards and reports.

Java
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class RicherGrouping {

    public static void main(String[] args) {
        var sales = Sale.sample();

        // Statistics in one pass
        Map<String, Double> avgRevenue = sales.stream()
                .collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                        Collectors.averagingDouble(Sale::revenue)));
        System.out.println("average revenue: " + avgRevenue);

        // Best element per group (maxBy returns Optional)
        Map<String, Optional<Sale>> biggest = sales.stream()
                .collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                        Collectors.maxBy(Comparator.comparingDouble(Sale::revenue))));
        biggest.forEach((region, sale) ->
                System.out.println("biggest in " + region + ": " + sale.get().product()));

        // collectingAndThen unwraps the Optional (groups are never empty)
        Map<String, String> topProduct = sales.stream()
                .collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparingDouble(Sale::revenue)),
                                s -> s.orElseThrow().product())));
        System.out.println("top product:     " + topProduct);

        // Distinct values per group
        Map<String, Set<String>> regionsByProduct = sales.stream()
                .collect(Collectors.groupingBy(Sale::product, TreeMap::new,
                        Collectors.mapping(Sale::region, Collectors.toCollection(TreeSet::new))));
        System.out.println("sold in:         " + regionsByProduct);

        // Two levels: region -> product -> units
        Map<String, Map<String, Integer>> nested = sales.stream()
                .collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                        Collectors.groupingBy(Sale::product, TreeMap::new,
                                Collectors.summingInt(Sale::units))));
        System.out.println("nested:          " + nested);

        // Two buckets only: partitioningBy
        Map<Boolean, Long> bigOrders = sales.stream()
                .collect(Collectors.partitioningBy(s -> s.revenue() >= 2000,
                        Collectors.counting()));
        System.out.println("revenue >= 2000: " + bigOrders);
    }
}

Output:

Output
average revenue: {east=950.0, north=2033.3333333333333, south=2900.0}
biggest in east: laptop
biggest in north: laptop
biggest in south: phone
top product:     {east=laptop, north=laptop, south=phone}
sold in:         {laptop=[east, north, south], phone=[north, south], tablet=[north]}
nested:          {east={laptop=1}, north={laptop=3, phone=4, tablet=6}, south={laptop=2, phone=10}}
revenue >= 2000: {false=4, true=2}
  • averagingDouble(Sale::revenue) computed the mean revenue per region.
  • maxBy returns an Optional per group. Since a group always has at least one element, collectingAndThen(maxBy(...), s -> s.orElseThrow().product()) safely unwraps it, giving the top product per region.
  • mapping(Sale::region, toSet()) listed the regions where each product sold.
  • A groupingBy inside a groupingBy built a two-level map: region, then product, then units.
  • partitioningBy splits into exactly two groups, true and false, and always contains both keys.

filtering, summarizing, joining and teeing

A second data set of orders, including a region where every order is small, shows the collectors added in Java 9 and 12 and a few useful combinations.

Java
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class MoreCollectors {

    record Order(String region, String product, double amount) {
    }

    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("north",
            "laptop", 1200), new Order("north", "pen", 3),
            new Order("south", "phone", 800), new Order("north", "phone", 750),
            new Order("south", "pen", 2), new Order("east", "pen", 4));

        // filtering (Java 9): keeps empty groups, unlike filter() before grouping
        Map<String, List<String>> bigOnly = orders.stream().collect(Collectors.groupingBy(
            Order::region, TreeMap::new, Collectors.filtering(o -> o.amount() > 100,
                Collectors.mapping(Order::product, Collectors.toList()))));
        Map<String, List<String>> filteredFirst = orders.stream().filter(o -> o.amount() > 100)
            .collect(Collectors.groupingBy(Order::region, TreeMap::new,
                Collectors.mapping(Order::product, Collectors.toList())));
        System.out.println("filtering():        " + bigOnly);
        System.out.println("filter() first:     " + filteredFirst);

        // summarizingDouble: count, sum, min, max and average in one pass
        Map<String, DoubleSummaryStatistics> stats = orders.stream().collect(
            Collectors.groupingBy(Order::region, TreeMap::new,
                Collectors.summarizingDouble(Order::amount)));
        DoubleSummaryStatistics north = stats.get("north");
        System.out.printf("north: count %d, sum %.0f, max %.0f, avg %.1f%n", north.getCount(),
            north.getSum(), north.getMax(), north.getAverage());

        // mapping to a Set, and joining
        Map<String, Set<String>> regionsPerProduct = orders.stream().collect(Collectors.groupingBy(
            Order::product, TreeMap::new, Collectors.mapping(Order::region, Collectors.toSet())));
        System.out.println("regions per product: " + regionsPerProduct);
        Map<String, String> joined = orders.stream().collect(Collectors.groupingBy(Order::region,
            TreeMap::new, Collectors.mapping(Order::product, Collectors.joining("+"))));
        System.out.println("joined:             " + joined);

        // teeing (Java 12): two collectors over the same elements, combined at the end
        String summary = orders.stream().collect(Collectors.teeing(
            Collectors.counting(),
            Collectors.summingDouble(Order::amount),
            (count, total) -> count + " orders, total " + total));
        System.out.println("teeing:             " + summary);
    }
}

Output:

Output
filtering():        {east=[], north=[laptop, phone], south=[phone]}
filter() first:     {north=[laptop, phone], south=[phone]}
north: count 3, sum 1953, max 1200, avg 651.0
regions per product: {laptop=[north], pen=[east, south, north], phone=[south, north]}
joined:             {east=pen, north=laptop+pen+phone, south=phone+pen}
teeing:             6 orders, total 2759.0
  • Collectors.filtering filters inside each group, so east, which has no order above 100, appears with an empty list. Filtering the stream before grouping removes east from the map entirely. Choose based on whether reports should show empty groups.
  • summarizingDouble collects count, sum, minimum, maximum and average in one pass, here 3 orders worth 1,953 in north.
  • mapping(..., toSet()) gives distinct values per group, in no particular order, and mapping(..., joining("+")) a single string per group.
  • teeing runs two collectors over the same elements and merges their results, here a count and a total in one pass without grouping at all.

Traps: null keys, Optionals and result types

A person with no city is the kind of data that breaks grouping code in production. The program shows that failure and three other things to watch.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

public class GroupingTraps {

    record Person(String name, String city) {
    }

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(new Person("ann", "Oslo"), new Person("bob", null),
            new Person("cy", "Lima"));

        // A null key throws
        try {
            people.stream().collect(Collectors.groupingBy(Person::city));
        } catch (NullPointerException e) {
            System.out.println("groupingBy with a null key: NullPointerException: "
                + e.getMessage());
        }
        Map<String, List<String>> safe = people.stream().collect(Collectors.groupingBy(
            p -> Objects.requireNonNullElse(p.city(), "unknown"),
            Collectors.mapping(Person::name, Collectors.toList())));
        System.out.println("with a placeholder key: " + new java.util.TreeMap<>(safe));

        // maxBy gives Optional values; collectingAndThen unwraps them
        Map<String, Optional<Person>> withOptional = people.stream()
            .filter(p -> p.city() != null)
            .collect(Collectors.groupingBy(Person::city,
                Collectors.maxBy(java.util.Comparator.comparing(Person::name))));
        System.out.println("maxBy values are Optionals: " + withOptional.get("Oslo"));

        // The default map and list types are not specified: ask for what you need
        Map<String, List<String>> grouped = people.stream().filter(p -> p.city() != null)
            .collect(Collectors.groupingBy(Person::city,
                Collectors.mapping(Person::name, Collectors.toCollection(ArrayList::new))));
        grouped.get("Oslo").add("dee");          // fine: we asked for ArrayList
        System.out.println("mutable groups: " + grouped.get("Oslo"));

        // counting() returns Long, not Integer
        Map<String, Long> counts = people.stream().filter(p -> p.city() != null)
            .collect(Collectors.groupingBy(Person::city, Collectors.counting()));
        Long oslo = counts.get("Oslo");
        System.out.println("counting() type: "
            + oslo.getClass().getSimpleName() + ", value " + oslo);
    }
}

Output:

Output
groupingBy with a null key: NullPointerException: element cannot be mapped to a null key
with a placeholder key: {Lima=[cy], Oslo=[ann], unknown=[bob]}
maxBy values are Optionals: Optional[Person[name=ann, city=Oslo]]
mutable groups: [ann, dee]
counting() type: Long, value 1
  • A classifier that returns null throws NullPointerException with "element cannot be mapped to a null key". Map missing keys to a placeholder such as "unknown", or filter those elements out first.
  • maxBy and minBy produce Optional values, which must be unwrapped, for example with collectingAndThen.
  • The documentation does not promise the type, mutability or thread-safety of the default map and lists. Ask explicitly: a map factory such as TreeMap::new, and toCollection(ArrayList::new) for groups you want to change later.
  • counting() returns Long. Assigning it to an Integer variable does not compile; use summingInt(x -> 1) if Integer counts are needed.

For parallel streams, groupingByConcurrent collects into a shared ConcurrentMap instead of merging per-thread maps, at the cost of ordering within groups.

What groupingBy does underneath, and choosing the map

A grouping collector is a loop over the elements with a map in the middle. For each element it computes the key, looks up that key's container with computeIfAbsent, creating one from the downstream collector's supplier if needed, and feeds the element to the downstream accumulator. At the end it applies the downstream finisher to every value. The program below writes that loop by hand and compares it with the collector, then shows three choices the collector leaves to you: the map type, the count type and the key.

Java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class LoopEquivalent {

    public static void main(String[] args) {
        List<Sale> sales = Sale.sample();

        // What groupingBy(region, mapping(product, toList())) does, written as a loop
        Map<String, List<String>> loop = new TreeMap<>();
        for (Sale s : sales) {
            loop.computeIfAbsent(s.region(), k -> new ArrayList<>()).add(s.product());
        }
        Map<String, List<String>> stream = sales.stream().collect(Collectors.groupingBy(
            Sale::region, TreeMap::new, Collectors.mapping(Sale::product, Collectors.toList())));
        System.out.println("loop:   " + loop);
        System.out.println("stream: " + stream + ", equal: " + loop.equals(stream));

        // Keys in first-seen order instead of sorted
        Map<String, Long> firstSeen = sales.stream().collect(Collectors.groupingBy(
            Sale::region, LinkedHashMap::new, Collectors.counting()));
        System.out.println("LinkedHashMap keys (first seen): " + firstSeen.keySet());

        // Integer counts instead of Long
        Map<String, Integer> intCounts = sales.stream().collect(Collectors.groupingBy(
            Sale::product, TreeMap::new, Collectors.summingInt(s -> 1)));
        System.out.println("summingInt(s -> 1): " + intCounts);

        // A key made of two fields: group by region and product at once
        record RegionProduct(String region, String product) {
        }
        Map<RegionProduct, Integer> units = sales.stream().collect(Collectors.groupingBy(
            s -> new RegionProduct(s.region(), s.product()), Collectors.summingInt(Sale::units)));
        System.out.println("north/phone units: " + units.get(new RegionProduct("north", "phone"))
            + " (" + units.size() + " region-product pairs)");
    }
}
Output
loop:   {east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]}
stream: {east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]}, equal: true
LinkedHashMap keys (first seen): [north, south, east]
summingInt(s -> 1): {laptop=3, phone=2, tablet=1}
north/phone units: 4 (6 region-product pairs)
  • The hand-written computeIfAbsent loop and the collector gave equal maps, {east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]}. Either is fine; the collector reads better once a downstream collector does real work.
  • With LinkedHashMap::new the keys came out as [north, south, east], the order in which each region first appeared in the data. Use it for reports that should follow the input order.
  • summingInt(s -> 1) produced Integer counts, {laptop=3, phone=2, tablet=1}, for code that cannot take the Long values that counting() returns.
  • A local record as the key grouped by two fields at once. The key for north and phone held 4 units, and the map had 6 entries, one per region and product pair. This is flatter than a nested groupingBy and easier to look up, because records supply equals and hashCode.

Choose a nested map when you will walk the result level by level, as in a report with a heading per region. Choose a record key when you will look up single combinations or sort them as one list.

Writing your own downstream collector

When no built-in collector answers the question, Collector.of builds one from four functions: a supplier that creates an empty container, an accumulator that adds one element, a combiner that merges two containers, and an optional finisher that turns the container into the result. A common need is the top N elements of each group. Sorting each group and taking N works, but it keeps every element; the collector below keeps a heap of at most N.

Java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class CustomCollector {

    // Collects the n largest elements, largest first, keeping only n at a time
    static <T> Collector<T, ?, List<T>> topN(int n, Comparator<? super T> cmp) {
        return Collector.of(
            () -> new PriorityQueue<T>(cmp),                  // supplier: a new container
            (heap, t) -> {                                    // accumulator: add one element
                heap.add(t);
                if (heap.size() > n) {
                    heap.poll();
                }
            },
            (h1, h2) -> {                                     // combiner: merge two containers
                for (T t : h2) {
                    h1.add(t);
                    if (h1.size() > n) {
                        h1.poll();
                    }
                }
                return h1;
            },
            heap -> {                                         // finisher: the final result
                List<T> out = new ArrayList<>(heap);
                out.sort(cmp.reversed());
                return out;
            });
    }

    public static void main(String[] args) {
        List<Sale> sales = Sale.sample();
        Map<String, List<String>> top2 = sales.stream().collect(Collectors.groupingBy(
            Sale::region, TreeMap::new,
            Collectors.collectingAndThen(topN(2, Comparator.comparingDouble(Sale::revenue)),
                list -> list.stream().map(s -> s.product() + "=" + s.revenue()).toList())));
        System.out.println("top 2 sales per region: " + top2);

        // The same collector works on a parallel stream: the combiner merges partial results
        List<Integer> top3 = java.util.stream.IntStream.range(0, 100000).boxed().parallel()
            .collect(topN(3, Comparator.naturalOrder()));
        System.out.println("top 3 of 0..99,999 in parallel: " + top3);
    }
}
Output
top 2 sales per region: {east=[laptop=950.0], north=[laptop=2700.0, tablet=1800.0], south=[phone=4000.0, laptop=1800.0]}
top 3 of 0..99,999 in parallel: [99999, 99998, 99997]
  • North kept its two largest sales, laptop=2700.0 and tablet=1800.0, and dropped the phone sale worth 1,600. South kept phone=4000.0 and laptop=1800.0.
  • East had only one sale, so its list holds one entry. A top N collector should never invent entries or fail when a group is smaller than N.
  • On a parallel stream of 100,000 numbers the result was [99999, 99998, 99997]. Each thread filled its own heap, and the combiner merged them; a wrong combiner is the usual reason a custom collector works sequentially but gives wrong answers in parallel.
  • The heap is a min-heap under the comparator, so poll removes the smallest of the kept elements. The finisher sorts the survivors with the reversed comparator so the largest comes first.

In practice the combiner runs only when a stream is parallel, so test any custom collector with parallel() at least once. Without a finisher, Collector.of marks the collector IDENTITY_FINISH and returns the container itself.

Performance: groupingBy, loops and groupingByConcurrent

Counting words is the classic grouping job. The program counts 2,000,000 strings that share 1,000 distinct keys in five ways. Each figure is the fastest of three runs, taken from a second round so the first round can warm up the JIT compiler.

Java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class GroupingSpeed {

    static boolean print;

    public static void main(String[] args) {
        // 2,000,000 words drawn from 1,000 distinct keys
        List<String> words = IntStream.range(0, 2000000)
            .mapToObj(i -> "w" + (i % 1000 * 7919 % 1000)).toList();
        System.out.printf("count %,d words with 1,000 distinct keys (best of 3, second round)%n",
            words.size());
        for (int round = 0; round < 2; round++) {
            print = round == 1;
            time("loop with merge", words, w -> {
                Map<String, Long> m = new HashMap<>();
                for (String s : w) {
                    m.merge(s, 1L, Long::sum);
                }
                return m;
            });
            time("groupingBy + counting", words, w -> w.stream()
                .collect(Collectors.groupingBy(s -> s, Collectors.counting())));
            time("toMap with merge function", words, w -> w.stream()
                .collect(Collectors.toMap(s -> s, s -> 1L, Long::sum)));
            time("parallel groupingBy", words, w -> w.parallelStream()
                .collect(Collectors.groupingBy(s -> s, Collectors.counting())));
            time("parallel groupingByConcurrent", words, w -> w.parallelStream()
                .collect(Collectors.groupingByConcurrent(s -> s, Collectors.counting())));
        }
    }

    static void time(String name, List<String> words, Function<List<String>, Map<String, Long>> f) {
        long best = Long.MAX_VALUE;
        Map<String, Long> result = null;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            result = f.apply(words);
            best = Math.min(best, System.nanoTime() - t0);
        }
        if (print) {
            System.out.printf("  %-30s %6.1f ms  (w0 -> %d)%n", name, best / 1e6,
                result.get("w0"));
        }
    }
}

Output (rough timings, 2-CPU Linux machine, JDK 21; the parallel lines vary most between runs):

Output
count 2,000,000 words with 1,000 distinct keys (best of 3, second round)
  loop with merge                  28.5 ms  (w0 -> 2000)
  groupingBy + counting            26.5 ms  (w0 -> 2000)
  toMap with merge function        34.1 ms  (w0 -> 2000)
  parallel groupingBy              27.3 ms  (w0 -> 2000)
  parallel groupingByConcurrent    53.0 ms  (w0 -> 2000)
  • The merge loop and groupingBy with counting() finished within a few percent of each other in every run. Choose between them for readability, not speed.
  • toMap with Long::sum was about 1.3 to 1.6 times slower than groupingBy across runs, because it boxes a new Long for each element before merging.
  • Plain groupingBy on a parallel stream ranged from about the same speed as the sequential version to about 1.8 times faster, depending on the run, on two CPUs. Each thread builds its own map, and the maps are merged at the end.
  • groupingByConcurrent was the slowest, 2 to 3 times slower than sequential groupingBy. All threads share one ConcurrentHashMap, and because counting() is not a concurrent collector, the JDK 21 source wraps each update to a group in synchronized on that group's container. With only 1,000 keys, threads keep meeting on the same locks.

groupingByConcurrent pays off when there are many keys, so collisions are rare, and when merging large per-thread maps would be expensive. Measure with your own data before switching to it.

Which collector to use

Choosing a grouping collector
Question per groupDownstream collector
Which elements?Default toList()
How many?counting()
Total or average of a field?summingInt, averagingDouble
All statistics at once?summarizingDouble
Only one field of each element?mapping(field, toList())
Distinct values?mapping(field, toSet())
The best element?collectingAndThen(maxBy(cmp), Optional::orElseThrow)
Only some elements, keeping empty groups?filtering(test, ...)
A second level of grouping?Another groupingBy
Two answers in one pass?teeing
Sorted keys?Add TreeMap::new as the map factory

Flattening inside groups uses flatMapping, shown on the flatMap page; enum keys fit an EnumMap factory, shown on EnumMap.