Posted in

What is the difference between map() and flatMap() in Java 8 Streams?

1. map()

  • Used to transform each element of a stream.
  • Each element is mapped to exactly one output element.

2. flatMap()

  • It “flattens” the nested structures into a single stream.
  • Useful when dealing with lists of lists, or streams of streams.

Great example! Let’s use an Employee class where:

  • Each employee has a single ID → (map() is suitable).
  • Each employee has multiple phone numbers → (flatMap() is required to flatten them).

Example: Using map() and flatMap() with Employee Data

package com.eazybytes.mapflatmap;

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

public class MapFlatMapExample {
    public static void main(String[] args) {
        List<Employee> employeeList = new ArrayList<>();
        employeeList.add(new Employee(Arrays.asList("1234567890", "9876543210"), 50000, "Developer", "Nisha Patel", 1));
        employeeList.add(new Employee(Arrays.asList("1234567891", "9876543211"), 55000, "Designer", "Arjun Rao", 2));
        employeeList.add(new Employee(Arrays.asList("1234567892", "9876543212"), 60000, "Manager", "Rahul Sharma", 3));
        employeeList.add(new Employee(Arrays.asList("1234567893", "9876543213"), 52000, "Analyst", "Priyanka Chopra", 4));
        employeeList.add(new Employee(Arrays.asList("1234567894", "9876543214"), 48000, "Tester", "Rohan Khanna", 5));

        List<Integer> employeeIdList = employeeList.stream().map(employee -> employee.getEid()).collect(Collectors.toList());
        System.out.println(employeeIdList);

        List<List<String>> employeePhoneList1 = employeeList.stream().map(employee -> employee.getPhoneNumbers()).collect(Collectors.toList());
        System.out.println("Issue: " + employeePhoneList1);

        List<String> employeePhoneList2 = employeeList.stream().flatMap(employee -> employee.getPhoneNumbers().stream()).collect(Collectors.toList());
        System.out.println("Solution: " + employeePhoneList2);

    }
}
Map output: [1, 2, 3, 4, 5]
Issue with map : [[1234567890, 9876543210], [1234567891, 9876543211], [1234567892, 9876543212], [1234567893, 9876543213], [1234567894, 9876543214]]
Solution: [1234567890, 9876543210, 1234567891, 9876543211, 1234567892, 9876543212, 1234567893, 9876543213, 1234567894, 9876543214]

📌 Understanding map() vs. flatMap()

Operation
Extract Employee IDs map()✅ Each Employee has one ID, so map() is used
Extract Employee Phone Numbers flatMap()✅ Each Employee has multiple phone numbers, so flatMap() is used to merge them

📝 Summary

  • map(Employee::getId): Each Employee has one ID → Produces a list of IDs.
  • flatMap(emp -> emp.getPhoneNumbers().stream()): Each Employee has multiple phone numbers, so we flatten them into a single list.

Key Differences

Featuremap()flatMap()
Output StructureOne-to-one mappingOne-to-many mapping (flattens)
ReturnsStream<T>Stream<R> (flattened)
Handles Nested StreamsNo, results in Stream<Stream<T>>Yes, converts Stream<Stream<T>> to Stream<T>

Leave a Reply

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