Collectors.groupingBy()
A collector that sorts elements into groups that share a key.
Available since: Java 8
Syntax
static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier)
static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)Parameters
| Parameter | Type | Description |
|---|---|---|
| classifier | Function<? super T, ? extends K> | Computes the group key for an element. |
| downstream | Collector<? super T, A, D> | Optional: what to gather inside each group (a list by default). |
Return value
Collector<T, ?, Map<K, D>>A collector into a map of groups.
Examples
Words by length:
void main() {
Map<Integer, List<String>> byLength = Stream.of("cat", "dog", "horse", "ox", "mouse")
.collect(Collectors.groupingBy(String::length));
IO.println(byLength);
}Output:
{2=[ox], 3=[cat, dog], 5=[horse, mouse]}Totals per category in a sorted map:
record Expense(String category, int amount) {}
void main() {
var expenses = List.of(new Expense("food", 30), new Expense("transport", 15),
new Expense("food", 12), new Expense("fun", 40));
Map<String, Integer> totals = expenses.stream()
.collect(Collectors.groupingBy(Expense::category, TreeMap::new,
Collectors.summingInt(Expense::amount)));
IO.println(totals);
}Output:
{food=42, fun=40, transport=15}Notes
By default the result is a HashMap whose values are lists of group elements. The second argument changes what a group holds: counting(), summingInt(), averagingDouble(), mapping(), toSet(). The three-argument version sets the map type, for example TreeMap::new for sorted keys.
See also
- Collectors.counting() — A counting collector, usually used inside `groupingBy()`.
- Collectors.partitioningBy() — Splits stream elements into two groups by a condition.
- Collectors.toMap() — A collector that builds a map from stream elements.
- Map.computeIfAbsent() — Returns the value for a key, creating it with a function if the key is absent.
Related recipes
In the tutorial
- Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.