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]
}
}
Output :
map() result:
[[JAVA, SPRING], [HIBERNATE, JPA]]
flatMap() result:
[JAVA, SPRING, HIBERNATE, JPA]
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)
Thanks, nice comparison
"flat"...map :)