What it is and why to use it
Data often arrives in nested groups: orders contain items, classes contain learners, and pages contain results. map can turn each group into another value but preserves one output per input. flatMap allows each input to supply a stream and flattens those streams into one sequence.
How it works
List::stream turns each inner list into its own stream. flatMap joins their elements into the downstream stream. Empty inner lists contribute no values. The terminal toList operation, available from Java 16, collects the encounter-ordered values into an unmodifiable list.
Common mistakes and limitations
map(List::stream) produces a stream of streams rather than a stream of names. Do not reuse a consumed stream or assume the result of Stream.toList is mutable.
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
groups.stream().flatMap(List::stream).toList()Examples
Flattening Nested Data with flatMap
Complete Main.java example — Java 17 or later, without preview features.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<List<String>> groups = List.of(
List.of("John", "James"), List.of(), List.of("Alex"));
List<String> names = groups.stream().flatMap(List::stream).toList();
System.out.println(names);
}
}- The outer list contains three groups, including an empty group.
- flatMap reads John and James from the first group, nothing from the second, and Alex from the third.
- toList triggers traversal and stores the flattened names. This is useful when displaying one combined result list from several pages or groups.
- Expected output: [John, James, Alex]
Best practices
- Use flatMap for one-to-many transformations.
- Keep mapping functions free of changes to their source collections.
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