DEV Community

realNameHidden
realNameHidden

Posted on • Edited on

Java 8 — map() vs flatMap()

side-by-side comparison of map() vs flatMap() on the same dataset so you can clearly see the difference in one run.

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

public class MapVsFlatMap {
    public static void main(String[] args) {
        List<List<String>> nestedList = Arrays.asList(
            Arrays.asList("java", "spring"),
            Arrays.asList("hibernate", "jpa")
        );

        // Using map()
        List<List<String>> mappedResult = nestedList.stream()
                .map(list -> list.stream()
                        .map(String::toUpperCase)
                        .collect(Collectors.toList())) // still a list inside a list
                .collect(Collectors.toList());

        System.out.println("map() result:");
        System.out.println(mappedResult); // [[JAVA, SPRING], [HIBERNATE, JPA]]

        // Using flatMap()
        List<String> flatMappedResult = nestedList.stream()
                .flatMap(list -> list.stream()) // flatten before collecting
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        System.out.println("\nflatMap() result:");
        System.out.println(flatMappedResult); // [JAVA, SPRING, HIBERNATE, JPA]
    }
}

Enter fullscreen mode Exit fullscreen mode

Output :

map() result:
[[JAVA, SPRING], [HIBERNATE, JPA]]

flatMap() result:
[JAVA, SPRING, HIBERNATE, JPA]

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

map() keeps the nested structure → List>.

flatMap() flattens the structure → List.

Both can transform elements, but flatMap() is the go-to when you want a single flat result from nested data.

Top comments (2)

Collapse
 
tintildev profile image
Martin Klestil

Thanks, nice comparison

Collapse
 
frc profile image
Fabrice René-Corail

"flat"...map :)