Java SE API
Collectors.groupingBy()
Classifies items and reduces each group with an explicit result map factory. Java SE API; example uses Java 21-compatible syntax.
Formal Syntax & Structure
java syntaxjava
static <T,K,D,A,M extends Map<K,D>> Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| classifier | Function<? super T,? extends K> | Group key |
| mapFactory | Supplier<M> | New empty map |
| downstream | Collector<? super T,A,D> | Per-group reduction |
Return Value
Collector<T,?,M>
Classifies items and reduces each group with an explicit result map factory.
Working Example
Example Snippetjava
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { record Stock(String category, int units) {} var stock = List.of(new Stock("paper", 4), new Stock("tools", 2), new Stock("paper", 6)); var totals = stock.stream().collect(Collectors.groupingBy(Stock::category, TreeMap::new, Collectors.summingInt(Stock::units))); System.out.println(totals); }}