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.

Programmer DD
Programmer DD
Programmer DD
Master Java 8 Stream: When to Use map vs flatMap

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavafunctional programmingMAPStream APIflatMapJava 8
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.