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

map is one to one. flatMap is one to many, and it flattens the result.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> sentences = List.of("java is fun", "streams are great");

        List<String[]> mapped = sentences.stream()
                .map(s -> s.split(" "))
                .toList();
        System.out.println(mapped.size() + " arrays");           // a list of arrays

        List<String> words = sentences.stream()
                .flatMap(s -> Arrays.stream(s.split(" ")))
                .toList();
        System.out.println(words);                                 // one flat list
    }
}
Output

2 arrays
[java, is, fun, streams, are, great]

See Java Streams.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.