flatMap for Nested Collections
Flatten nested lists, Optional chains, and file-line structures using flatMap.
flatMap for Nested Collections is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Nested Collection Problem
When each element of a stream maps to another collection, map gives you a Stream<List<T>>. flatMap merges the inner streams into one flat Stream<T>.
List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4), List.of(5));
// With map:
Stream<List<Integer>> s = nested.stream().map(l -> l); // Stream<List<Integer>>
// With flatMap:
Stream<Integer> flat = nested.stream().flatMap(List::stream); // Stream<Integer>
flat.forEach(System.out::println); // 1 2 3 4 5flatMap vs map
map(f) applies f to each element and wraps the result. flatMap(f) applies f which returns a stream, then concatenates all those streams into one.
// map: List<String> -> Stream<Stream<Character>>
Stream<Stream<Character>> nested = List.of("hi","bye").stream()
.map(s -> s.chars().mapToObj(c -> (char)c));
// flatMap: List<String> -> Stream<Character>
Stream<Character> flat = List.of("hi","bye").stream()
.flatMap(s -> s.chars().mapToObj(c -> (char)c));Flattening Orders and Items
Classic use: each order has a list of items. Get a flat stream of all items across all orders.
List<String> allItems = orders.stream()
.flatMap(order -> order.getItems().stream())
.collect(Collectors.toList());
System.out.println(allItems);flatMap with Optional
Use stream() on Optional (Java 9+) to convert it to a 0- or 1-element stream. Then flatMap collapses a Stream<Optional<T>> into Stream<T>.
List<Optional<String>> maybes = List.of(Optional.of("a"), Optional.empty(), Optional.of("c"));
List<String> values = maybes.stream()
.flatMap(Optional::stream) // Java 9+
.collect(Collectors.toList());
System.out.println(values); // [a, c]Reading All Lines from Multiple Files
flatMap makes it easy to concatenate all lines from a list of files into one stream without nested loops.
List<Path> files = List.of(Path.of("a.txt"), Path.of("b.txt"));
List<String> allLines = files.stream()
.flatMap(p -> {
try { return Files.lines(p); }
catch (IOException e) { return Stream.empty(); }
})
.collect(Collectors.toList());Splitting Strings into Words
Split each sentence into words and flatten all words into a single stream for word frequency counting.
List<String> sentences = List.of("hello world", "java streams rock");
Map<String, Long> freq = sentences.stream()
.flatMap(s -> Arrays.stream(s.split("\\s+")))
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
System.out.println(freq);flatMap with Map.entrySet
Flatten a map of categories to lists of items into a stream of all items.
Map<String, List<String>> catalog = Map.of(
"fruit", List.of("apple","banana"),
"veg", List.of("carrot","pea"));
List<String> all = catalog.values().stream()
.flatMap(List::stream)
.sorted()
.collect(Collectors.toList());
System.out.println(all); // [apple, banana, carrot, pea]Avoiding NullPointerException in flatMap
If the function may return null instead of a stream, guard with a null check or return Stream.empty() to avoid NullPointerException.
departments.stream()
.flatMap(dept -> dept.getEmployees() == null
? Stream.empty()
: dept.getEmployees().stream())
.forEach(System.out::println);Counting Distinct Words with flatMap
Combine flatMap, distinct, and count for concise data processing.
long distinctWords = sentences.stream()
.flatMap(s -> Arrays.stream(s.toLowerCase().split("[^a-z]+")))
.filter(w -> !w.isEmpty())
.distinct()
.count();
System.out.println("Distinct: " + distinctWords);flatMapToInt for Primitive Streams
Use flatMapToInt, flatMapToLong, and flatMapToDouble to avoid boxing when flattening into primitive streams.
int totalQuantity = orders.stream()
.flatMapToInt(order -> order.getItems().stream().mapToInt(Item::getQuantity))
.sum();
System.out.println("Total qty: " + totalQuantity);Performance Note
Each flatMap call adds a stream layer. For very large datasets with many small inner collections, consider iterative approaches or Spliterator to reduce object creation overhead.
Quick Check
What does flatMap do differently from map?
Recap
flatMap converts each element to a stream and merges all streams into one. Use it to flatten nested collections, chain Optionals, split strings, and read multiple files. Use flatMapToInt to avoid boxing.
Frequently asked questions
Is the “flatMap for Nested Collections” lesson free?
Yes — the full text of “flatMap for Nested Collections” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “flatMap for Nested Collections”?
Flatten nested lists, Optional chains, and file-line structures using flatMap. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “flatMap for Nested Collections” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.