Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is the difference between map and flatMap in Java streams?

SHORT ANSWER

map transforms each element into exactly one new element. flatMap transforms each element into a stream and then merges all those streams into one flat stream, which is how you unpack lists inside lists.

Explain it simply

Suppose every student hands you a bag of pens. map is counting each bag, so you end up with a list of numbers. flatMap is emptying every bag onto one table so you have a single pile of pens.

Example

java
import java.util.*;
import java.util.stream.*;

List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(4, 5));

List<Integer> sizes = nested.stream()
        .map(List::size)
        .toList();
System.out.println(sizes);                 // prints: [2, 1, 2]

List<Integer> flat = nested.stream()
        .flatMap(List::stream)
        .map(n -> n * 10)
        .toList();
System.out.println(flat);                  // prints: [10, 20, 30, 40, 50]

What to say in the interview

"map is one-to-one, so a Stream<T> stays the same length. flatMap is one-to-many: the function must return a Stream, and the results are concatenated. A typical use is turning a list of orders into a stream of all their items, or splitting lines into words with line.split(' ') wrapped by Arrays.stream. With plain map I would be left with a Stream of Streams."

Common mistakes

  • Using map where the function already returns a collection, then getting a List of Lists.

#java#java8#streams

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.