Java Reference ยท Streams and Functional
Collectors.groupingBy() method
Reference for Java Collectors.groupingBy(): group stream elements by a key into a Map, use downstream collectors, choose the map type and count per group.
Collectors.groupingBy(classifier) sorts the elements of a stream into groups, like GROUP BY in SQL. The classifier function computes a key for each element, and the result is a Map from each key to a List of the elements that produced it.
The real power is the downstream collector: a second collector that decides what to do with each group's elements instead of listing them. Count them, sum a field, join strings, take the maximum, or group again for a nested map.
Map<Integer, List<String>> byLength = words.stream().collect(Collectors.groupingBy(String::length));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
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) 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)
| Name | Description |
|---|---|
classifier |
Returns the group key for an element. Must not return null. |
mapFactory |
Creates the result map, e.g. TreeMap::new or LinkedHashMap::new. |
downstream |
Reduces each group; defaults to toList(). |
Returns: a collector producing the map. A key exists only if at least one element mapped to it.
Usage notes
- Map order: the default map is a
HashMap-like type with no guaranteed order. PassTreeMap::newfor sorted keys orLinkedHashMap::newfor first-seen order. - No empty groups: keys with no elements are absent. For a true/false split that always has both keys use
partitioningBy(). - Downstream choices:
counting()(aLong),summingInt,averagingInt,mapping,filtering,maxBy,joining,toSet, or anothergroupingBy. - Order inside groups follows encounter order of the stream for sequential streams.
OptionalfrommaxBy: wrap withcollectingAndThen(maxBy(...), Optional::get)if you know groups are never empty.- Parallel:
groupingByConcurrentbuilds aConcurrentMapand is faster in parallel when encounter order does not matter. - Alternative:
Map.computeIfAbsent(key, k -> new ArrayList<>()).add(x)in a loop is equivalent and sometimes clearer; seecomputeIfAbsent.