Master Java 8 Stream: When to Use map vs flatMap
This tutorial explains how Java 8's Stream API's map and flatMap operations work, showing practical examples of extracting student ages from collections and demonstrating why flatMap is needed to flatten nested lists, with clear code snippets and diagrams.
1. Introduction
Java 8 provides a powerful Stream API that makes collection processing easy. This article explores two intermediate Stream operations: map and flatMap.
2. map operation
The map operation transforms each element in a stream into a new element, producing a new stream. For example, extracting ages from a list of Student objects can be done with a simple map instead of manual iteration.
Illustration:
Pseudocode:
// pseudocode
List<Integer> ages = studentList.stream()
.map(Student::getAge)
.collect(Collectors.toList());3. flatMap operation
While map is straightforward, flatMap is used when each element itself yields a collection that should be flattened into a single stream. For instance, extracting ages from all students across multiple classes.
Using map would give a List<List<Student>>, requiring nested loops. flatMap can flatten the inner lists first, then map to ages.
Pseudocode:
// flatMap extracts List<Students>, map extracts ages
List<Integer> ages = grades.stream()
.flatMap(grade -> grade.getStudents().stream())
.map(Student::getAge)
.collect(Collectors.toList());Thus, flatMap first creates a smaller stream for each inner collection and then merges them into one stream, unlike map which only transforms elements.
4. Summary
Once familiar with map and flatMap, you can solve many data‑flow problems easily. These operations also exist in Optional<T> with similar behavior.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
