Flatten nested data with flatMap
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Each customer has a list of orders, so you hold a list of lists. How do you get one simple list of every order?
The problem: lists inside a list
flatMap turns each element into a stream and joins all those streams into one, flattening nested data such as a list of lists.
A class keeps the subjects of each student as a list, so the whole class is a List<List<String>>: [[Maths, Physics], [Maths, Chemistry, Biology], [English]]. The timetable office wants one plain list of every subject taken.
Example 1 · Nested loop versus flatMap
import java.util.ArrayList;import java.util.List;
public class FlattenSubjectsDemo { public static void main(String[] args) { List<List<String>> classSubjects = List.of( List.of("Maths", "Physics"), List.of("Maths", "Chemistry", "Biology"), List.of("English"));
List<String> loopResult = new ArrayList<>(); for (List<String> subjects : classSubjects) { for (String subject : subjects) { loopResult.add(subject); } } System.out.println("Loop: " + loopResult);
List<String> all = classSubjects.stream() .flatMap(subjects -> subjects.stream()) .toList(); System.out.println("flatMap: " + all); System.out.println("Sizes: " + classSubjects.size() + " lists, " + all.size() + " subjects"); }}Loop: [Maths, Physics, Maths, Chemistry, Biology, English] flatMap: [Maths, Physics, Maths, Chemistry, Biology, English] Sizes: 3 lists, 6 subjects
What this code does
- The inner loop is exactly what
flatMapdoes for you: it opens each inner list and passes its items on, in order. - Three lists went in and six subjects came out.
flatMapcan change the number of elements;mapcannot. - Why: both visit each subject once.
flatMapreplaces the nested loop and theadd, so the whole line says "all subjects in one list".
With loops you need two of them, one inside the other: the outer loop walks the students, the inner loop walks each student's subjects and adds them to one result list. map cannot do this. It is strictly one in, one out, so each inner list stays a list. flatMap opens each inner list and pours its elements into one stream: classSubjects.stream().flatMap(list -> list.stream()).
How flatMap works, step by step
The function you give flatMap must return a stream for each element: Function<T, Stream<R>>. flatMap then takes the elements out of each small stream, in order, and passes them on one by one. The small streams themselves disappear; that is the "flat" part.
- The first element
[Maths, Physics]arrives. The function returns a stream ofMaths, Physics, and both go on. - The second element
[Maths, Chemistry, Biology]arrives. Its stream adds three more:Maths, Chemistry, Biology. - The third element
[English]addsEnglish. An empty inner list would add nothing at all. - The result is one stream of six Strings,
[Maths, Physics, Maths, Chemistry, Biology, English], ready forfilter,maportoList().
Example 2 · Records with a list inside: all subject enrolments
import java.util.List;
record Student(String name, List<String> subjects) {}
public class EnrolmentDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", List.of("Maths", "Physics")), new Student("Ravi", List.of("Maths", "Chemistry", "Biology")), new Student("Meena", List.of()), new Student("Kiran", List.of("English", "Maths")));
List<String> enrolments = students.stream() .flatMap(s -> s.subjects().stream()) .toList(); System.out.println("Enrolments: " + enrolments);
long maths = students.stream() .flatMap(s -> s.subjects().stream()) .filter(sub -> sub.equals("Maths")) .count(); System.out.println("Maths seats needed: " + maths); }}Enrolments: [Maths, Physics, Maths, Chemistry, Biology, English, Maths] Maths seats needed: 3
What this code does
- Each
Studentis opened into a stream of its subjects. Meena has none, so her empty stream adds nothing and causes no error. - After
flatMapthe stream is a plainStream<String>, so ordinaryfilterandcountwork on it.
flatMap is one in, any number out, while map is always one in, one out.Splitting lines into words
Text arrives as lines, but most questions, such as how many words or which is most common, are about words. Each line becomes many words, so this is a flatMap job: lines.stream().flatMap(line -> Arrays.stream(line.split(" "))).
Example 3 · Lines to words: a word count
import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.TreeMap;
public class WordCountDemo { public static void main(String[] args) { List<String> feedback = List.of( "UPI payment failed", " refund not received for UPI", "payment received thanks");
List<String> words = feedback.stream() .flatMap(line -> Arrays.stream(line.split("\\s+"))) .filter(w -> !w.isEmpty()) .map(String::toLowerCase) .toList(); System.out.println("Words: " + words.size()); System.out.println(words);
Map<String, Integer> counts = new TreeMap<>(); for (String w : words) { counts.merge(w, 1, Integer::sum); } System.out.println(counts); }}Words: 11
[upi, payment, failed, refund, not, received, for, upi, payment, received, thanks]
{failed=1, for=1, not=1, payment=2, received=2, refund=1, thanks=1, upi=2}What this code does
split("\\s+")cuts on any run of spaces. The second line starts with spaces, which gives an empty first word, so thefilterremoves it.flatMapturns 3 lines into 11 words. ATreeMapthen counts each word in A to Z order;merge(w, 1, Integer::sum)adds 1 to the old count.
Real text is messy. Split on "\\s+" (one or more spaces) instead of a single space, turn words to lowercase so UPI and upi match, and filter out empty Strings. A line that starts with a space gives an empty first word after split.
Arrays.stream turns the array returned by split into a stream. The flat stream can then be counted, filtered or collected. Counting each word separately is easy with a TreeMap loop for now; the Stream Collectors module does it in one step with groupingBy.
Trap: map gives a stream of streams
A common slip is to write map(list -> list.stream()) where flatMap was meant. The code compiles, but the result is a Stream<Stream<String>>: a stream whose elements are themselves streams.
Example 4 · Trap: map gives Stream<Stream<String>>
import java.util.List;
public class MapNotFlatDemo { public static void main(String[] args) { List<List<String>> classSubjects = List.of( List.of("Maths", "Physics"), List.of("English"));
List<String> all = classSubjects.stream() .map(subjects -> subjects.stream()) .toList(); System.out.println(all); }}MapNotFlatDemo.java:11: error: incompatible types: List<Stream<String>> cannot be converted to List<String>
.toList();
^
1 errorWhat this code does
- The function returns a stream, and
mapkeeps it as one element. The result is aList<Stream<String>>, which cannot go into aList<String>. - Change
maptoflatMapand the inner streams are opened and joined, so the result is a realList<String>.
You find out later. toList() gives a List<Stream<String>>, which does not fit a List<String> variable, and printing it shows object addresses like ReferencePipeline$Head@1b6d3586 instead of subjects. Whenever your function returns a stream, a list or an array per element, you want flatMap.
map versus flatMap
Both take a function and run it on every element. The difference is what the function returns and what happens to it.
Example 5 · map versus flatMap on the same data
import java.util.Arrays;import java.util.List;import java.util.stream.Stream;
record Contact(String name, String phones) {}
public class MapVersusFlatMapDemo { public static void main(String[] args) { List<String> lines = List.of("good morning class", "submit the lab record");
List<Integer> wordsPerLine = lines.stream() .map(line -> line.split(" ").length) .toList(); System.out.println("map: " + wordsPerLine);
List<String> allWords = lines.stream() .flatMap(line -> Arrays.stream(line.split(" "))) .toList(); System.out.println("flatMap: " + allWords);
List<Contact> contacts = List.of( new Contact("Asha", "98450 11111;80 2222 3333"), new Contact("Ravi", ""), new Contact("Meena", "99000 44444")); List<String> numbers = contacts.stream() .flatMap(c -> c.phones().isEmpty() ? Stream.empty() : Arrays.stream(c.phones().split(";"))) .toList(); System.out.println("Numbers to call: " + numbers); }}map: [3, 4] flatMap: [good, morning, class, submit, the, lab, record] Numbers to call: [98450 11111, 80 2222 3333, 99000 44444]
What this code does
mapgives one value per line (its word count), so 2 lines give 2 numbers.flatMapgives every word, so 2 lines give 7 words.- Asha has two numbers, Ravi has none and Meena has one. Returning
Stream.empty()for Ravi adds nothing, soflatMapcan also drop elements.
map: function returns one value per element;Stream<T>becomesStream<R>; count stays the same.flatMap: function returns a stream per element; all those streams are joined into oneStream<R>; count can grow or shrink.- Use
mapfor "change each thing", such as name to uppercase, price to price with GST. - Use
flatMapfor "open each thing", such as student to subjects, order to items, line to words.
Predict the output
map or flatMap?
Read the code, then pick what it prints.
Round 1 of 2
Next step
Check your understanding
12 quick questions