Java 25 (LTS) reference · Stream API

Java Collectors.groupingBy() Method

Group elements into a Map by a key function, optionally counting or summing each group.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

stream.collect(Collectors.groupingBy(classifier, downstream))

Parameters

ParameterDescription
classifier
Function<T, K>
Computes each element's group key.
downstream optional
Collector
What to collect per group, e.g. counting().

Return value

A Map<K, List<T>> (or the downstream result).

Examples

Group words by length
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("tea", "mug", "kettle", "cup", "spoon");
        Map<Integer, List<String>> byLength = words.stream().collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
        System.out.println(byLength);
    }
}

Output

{3=[tea, mug, cup], 5=[spoon], 6=[kettle]}

Run this on your computer — see “Get Started” for setup.

Count and sum per group
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        record Order(String customer, double total) {}
        List<Order> orders = List.of(new Order("ana", 20), new Order("ben", 5), new Order("ana", 7.5));
        Map<String, Long> counts = orders.stream().collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.counting()));
        Map<String, Double> totals = orders.stream().collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.summingDouble(Order::total)));
        System.out.println(counts);
        System.out.println(totals);
    }
}

Output

{ana=2, ben=1}
{ana=27.5, ben=5.0}

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?