Difference Between map() and flatMap() in Java Streams

Both map() and flatMap() are used for transformation in Java Streams, but they behave differently when handling nested structures (like Lists of Lists).

Featuremap()flatMap()
PurposeTransforms each element individuallyFlattens and transforms nested structures
Output TypeProduces a Stream of Streams (nested)Produces a flattened Stream
Use CaseWhen each element is transformed independentlyWhen each element contains collections and needs flattening
Common ExampleConvert elements (e.g., List of Strings to uppercase)Convert a List of Lists into a single List

1. map() Example (No Flattening)

It applies a function to each element, without flattening nested structures.

Example: Convert Each String to Uppercase

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {
    public static void main(String[] args) {
        List words = Arrays.asList("java", "stream", "map");

        // Transform each word to uppercase
        List result = words.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());

        System.out.println(result);
    }
}

Output

[JAVA, STREAM, MAP]

map() keeps the structure intact, transforming elements but not merging them.

2. flatMap() Example (Flattening a Nested List)

It flattens multiple lists into a single stream before applying transformation.

Example: Flatten a List of Lists

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FlatMapExample {
    public static void main(String[] args) {
        List<List<String>> listOfLists = Arrays.asList(
            Arrays.asList("java", "python"),
            Arrays.asList("c++", "javascript"),
            Arrays.asList("go", "rust")
        );

        // Flatten and collect into a single list
        List<String> flattenedList = listOfLists.stream()
                                                .flatMap(List::stream)
                                                .collect(Collectors.toList());

        System.out.println(flattenedList);
    }
}

Output

[java, python, c++, javascript, go, rust]

flatMap() combines nested elements into a single list.
List<List<String>>List<String>

3. Key Difference in map() vs flatMap() Output

If we use map() instead of flatMap(), we get List of Streams, not a single list.

List<Stream<String>> mapped = listOfLists.stream()
                                         .map(List::stream)
                                         .collect(Collectors.toList());

Output (Nested Streams, Not Flattened):

[Stream@1a2b3c4d, Stream@5e6f7g8h, Stream@9i0j1k2l]

flatMap() solves this by merging the streams into one.

4. When to Use map() vs. flatMap()

ScenarioUse map()Use flatMap()
Transforming elements one by oneYesNo
Dealing with nested collectionsNoYes
Convert List of Strings to uppercaseYesNo
Flattening List of ListsNoYes

Conclusion

Use map() when transforming individual elements.
Use flatMap() when working with nested structures and needing flattening.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *