Java Snippet

Group by Key with Stream Collectors

Difficulty: Medium

`Collectors.groupingBy` is the Java equivalent of SQL `GROUP BY`: pass a key extractor and you get back a `Map<K, List<T>>`. This snippet covers the basic grouping, downstream collectors (counting, summing, mapping to a different value), and multi-level grouping by chaining two `groupingBy` calls. Pair with `LinkedHashMap` when you need stable insertion order.

Code Snippets
/

Group by Key with Stream Collectors

Group by Key with Stream Collectors

`Collectors.groupingBy` is the Java equivalent of SQL `GROUP BY`: pass a key extractor and you get back a `Map<K, List<T>>`. This snippet covers the basic grouping, downstream collectors (counting, summing, mapping to a different value), and multi-level grouping by chaining two `groupingBy` calls. Pair with `LinkedHashMap` when you need stable insertion order.

Java
Medium
3 snippets
java-streams
java-collections
implementation

310 views

7

Collectors.groupingBy(keyExtractor) walks the stream once and bins each element under the key returned by the extractor. The default downstream collector is toList, so the value type is List<T>. The result is a HashMap, which means key iteration order is not stable: pass groupingBy(key, LinkedHashMap::new, toList()) if you need insertion order. On JDK 16+ the Order class collapses to record Order(String customer, String product, int qty) {}.