groupingBy collector¶
The groupingBy collector is a static method provided by the java.util.stream.Collectors class, designed for use with the Stream.collect() method to categorize elements in a stream based on a specific classification function^[600-developer__java__java8__java8-collect.md].
Functionality¶
The primary mechanism of groupingBy is to organize a stream of elements into a structure where elements are grouped by a specific key derived from the element itself^[600-developer__java__java8__java8-collect.md]. This is achieved by passing a function (often a method reference) that defines the grouping criteria.
Standard Grouping¶
The most common usage involves passing a single function argument. For example, grouping a list of Student objects by their name would use the syntax Collectors.groupingBy(Student::getName).^[600-developer__java__java8__java8-collect.md]
Grouping with Downstream Collector¶
A second overload of groupingBy allows for a two-argument signature: groupingBy(Function, Collector).^[600-developer__java__java8__java8-collect.md] The second argument is a "downstream collector" that performs a reduction operation on the values associated with each key. A common use case is to count the number of elements in each group using Collectors.counting()^[600-developer__java__java8__java8-collect.md].
Grouping with Custom Map Supplier¶
A third variant allows for the specification of a custom map implementation via the signature groupingBy(Function, Supplier, Collector).^[600-developer__java__java8-collect.md] This provides control over the specific type of Map used to store the grouped results (e.g., HashMap, TreeMap) alongside the classification function and downstream collector.
Concurrent Grouping¶
For parallel streams, the groupingByConcurrent(Function) method is available^[600-developer__java__java8__java8-collect.md]. This performs a similar operation to standard groupingBy but is optimized for concurrent processing.
Related Concepts¶
- [[Stream (Java)]]
- [[PartitioningBy]]
- [[Collector]]
Sources¶
^[600-developer__java__java8__java8-collect.md]