The groupingBy() method in Java streams groups elements by a specified property, similar to SQL's GROUP BY clause. It collects elements into a Map, with keys as the grouping criteria and values as lists or aggregated results.
- Group elements based on a specified property.
- Returns a Map of key, list/aggregated values.
- Supports aggregations like counting, summing, or averaging
Explanation:
- Groups numbers based on their own value.
- Uses Collectors.counting() to count the occurrences.
- Returns a Map<Integer, Long>, where the key is the number, and the value is its frequency.
- Demonstrates the second overload of groupingBy() (with downstream collector).
Variants of groupingBy() Method
The groupingBy() method is overloaded three times in Java:
1. Simple groupingBy
Group Elements into a List
Output{geeks=[geeks, geeks], for=[for]}
Explanation:
- Groups words by their value.
- Values are collected as lists of elements.
- Uses the simplest overload of groupingBy().
- Useful when you need all grouped elements, not aggregated results.
Syntax:
public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(
Function<? super T, ? extends K> classifier
)
Parameters:
- T: Type of input elements
- K: Type of key for grouping
- classifier: Function to extract the key from elements
2. groupingBy with Downstream Collector
Aggregate Elements per Key
Explanation:
- Groups words by their value.
- Uses Collectors.counting() to count frequency of each key.
- Returns a Map<String, Long>.
- Allows aggregation instead of collecting elements into a list.
Syntax:
public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(
Function<? super T, ? extends K> classifier,
Collector<? super T, A, D> downstream
)
Parameters:
- T: Type of input elements.
- K: Type of key for grouping.
- A: Intermediate accumulation type of downstream collector.
- D: Final result type of downstream collector.
- classifier: Function to extract the key.
- downstream: Collector to perform aggregation on grouped elements.
3. groupingBy with Map Supplier and Downstream Collector
Explanation:
- Groups words by value.
- Uses TreeMap to store keys in sorted order.
- Aggregates values using Collectors.counting().
- Returns a custom map type, useful when key order matters.
Syntax:
public static <T, K, D, M extends Map<K,D>> Collector<T, ?, M> groupingBy(
Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory,
Collector<? super T, ?, D> downstream
)
Parameters:
- T: Type of input elements.
- K: Type of key for grouping.
- D: Type of result of downstream collector.
- M: Type of Map to create.
- classifier: Function to extract key.
- mapFactory: Supplier to create a Map (e.g., TreeMap::new).
- downstream: Collector to perform aggregation.