Skip to lesson

Flatten nested data with flatMap

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

FlattenSubjectsDemo.javaJava
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");    }}
Output
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 flatMap does for you: it opens each inner list and passes its items on, in order.
  • Three lists went in and six subjects came out. flatMap can change the number of elements; map cannot.
  • Why: both visit each subject once. flatMap replaces the nested loop and the add, 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.

  1. The first element [Maths, Physics] arrives. The function returns a stream of Maths, Physics, and both go on.
  2. The second element [Maths, Chemistry, Biology] arrives. Its stream adds three more: Maths, Chemistry, Biology.
  3. The third element [English] adds English. An empty inner list would add nothing at all.
  4. The result is one stream of six Strings, [Maths, Physics, Maths, Chemistry, Biology, English], ready for filter, map or toList().
flatMap flattens lists. Asha has Maths, Physics; Ravi has Maths, Chemistry, Biology; Meena has none; Kiran has English, Maths. flatMap(s -> s.subjects().stream()) joins them into one stream of 7 subjects, three of them Maths.

Example 2 · Records with a list inside: all subject enrolments

EnrolmentDemo.javaJava
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);    }}
Output
Enrolments: [Maths, Physics, Maths, Chemistry, Biology, English, Maths]
Maths seats needed: 3

What this code does

  • Each Student is opened into a stream of its subjects. Meena has none, so her empty stream adds nothing and causes no error.
  • After flatMap the stream is a plain Stream<String>, so ordinary filter and count work on it.
Each element can give zero, one or many results. So 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

WordCountDemo.javaJava
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);    }}
Output
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 the filter removes it.
  • flatMap turns 3 lines into 11 words. A TreeMap then 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>>

MapNotFlatDemo.javaJava
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);    }}
Sample compiler output
MapNotFlatDemo.java:11: error: incompatible types: List<Stream<String>> cannot be converted to List<String>
                .toList();
                       ^
1 error

What this code does

  • The function returns a stream, and map keeps it as one element. The result is a List<Stream<String>>, which cannot go into a List<String>.
  • Change map to flatMap and the inner streams are opened and joined, so the result is a real List<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

MapVersusFlatMapDemo.javaJava
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);    }}
Output
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

  • map gives one value per line (its word count), so 2 lines give 2 numbers. flatMap gives 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, so flatMap can also drop elements.
  • map: function returns one value per element; Stream<T> becomes Stream<R>; count stays the same.
  • flatMap: function returns a stream per element; all those streams are joined into one Stream<R>; count can grow or shrink.
  • Use map for "change each thing", such as name to uppercase, price to price with GST.
  • Use flatMap for "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

List<List<String>> orders = List.of(
List.of("Pen", "Ruler"), List.of("Pen"), List.of("Notebook", "Pen", "Ruler"));
System.out.println(orders.stream().map(List::size).count());
System.out.println(orders.stream().flatMap(List::stream).count());

Next step

Check your understanding

12 quick questions