Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collectors.groupingBy: practical reference

Collectors.groupingBy: practical reference: Collectors.groupingBy classifies each element by a key function and accumulates a Map from keys to group results; its overloads select the map supplier and downstream collector.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Collectors.groupingBy(...)

Collectors.groupingBy classifies each element by a key function and accumulates a Map from keys to group results; its overloads select the map supplier and downstream collector.

Use it for indexes and summaries such as grouping words by length or orders by customer.

The Java SE API does not guarantee support for null classification keys, so the classifier must not return null; the verified OpenJDK 21 implementation rejects one with NullPointerException. The one-argument overload promises neither a Map implementation nor thread safety.

An empty stream produces an empty map. Encounter order inside group lists follows the downstream collector, while key iteration order is not guaranteed by the simple overload.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var grouped = java.util.stream.Stream.of("a", "bb", "c")
                .collect(java.util.stream.Collectors.groupingBy(String::length, java.util.TreeMap::new, java.util.stream.Collectors.toList()));
        System.out.println(grouped);
    }
}

Result

{1=[a, c], 2=[bb]}

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources