Codectionary / Developer documentation / Java

Grouping Stream Results with groupingBy

Collect elements into groups using a key calculated from each element.

What it is and why to use it

groupingBy collects elements with matching keys into the same result group. A classifier function calculates a key for each element. This is useful for grouping orders by status, learners by course or words by length without manually maintaining lists for each key.

How it works

The three-argument overload chooses a map implementation and a downstream collector. Here String::length calculates the key, TreeMap::new requests sorted numeric keys, and Collectors.toList stores the words for each length. The simple groupingBy overload does not guarantee the map’s iteration order.

Common mistakes and limitations

Do not rely on default HashMap-style ordering. groupingBy is not a promise of a concurrent map, and a null classifier result is not accepted by this collector.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

collect(Collectors.groupingBy(classifier, TreeMap::new, Collectors.toList()))

Examples

Grouping Stream Results with groupingBy

Complete Main.java example — Java 17 or later, without preview features.

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    Map<Integer, List<String>> groups = List.of("cat", "java", "dog").stream()
        .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
    System.out.println(groups);
  }
}
  1. cat and dog both produce key 3, so they share one group.
  2. java produces key 4. TreeMap makes the printed keys ascend from 3 to 4.
  3. The downstream list keeps the words within each group in encounter order. A report could replace the list collector with counting to calculate totals per group.
  4. Expected output: {3=[cat, dog], 4=[java]}

Best practices

  • Select a map factory when order is important.
  • Choose a downstream collector that matches the report’s result shape.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading