Java Stream flatMap() Method

The flatMap() method in Java is a part of the java.util.stream.Stream interface. In this guide, we will learn how to use flatMap() method in Java with practical examples and real-world use cases to better understand its usage.

Table of Contents

  1. Introduction
  2. flatMap() Method Syntax
  3. Examples
    • Basic Usage
    • Using flatMap() with Nested Structures
  4. Real-World Use Case
  5. Conclusion

Introduction

The Stream.flatMap() method in Java is used to transform each element of a stream into another stream and then merge all those streams into a single stream. It is helpful when working with nested data structures, like lists within lists.

This method flattens the nested structure, allowing you to work with all the inner elements in a single stream.

flatMap() is commonly used to handle collections of collections, such as processing a list of lists, and enables more complex data transformations.

flatMap() Method Syntax

The syntax for the flatMap() method is as follows:

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

Parameters:

  • mapper: A function to apply to each element, which produces a stream of new values.

Returns:

  • A new Stream consisting of the flattened results of the mapped streams.

Throws:

  • This method does not throw any exceptions.

Examples

Basic Usage

To demonstrate the basic usage of flatMap(), we will create a Stream of lists and use flatMap() to flatten these lists into a single stream of elements.

Example

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

public class FlatMapExample {
    public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(1, 2, 3);
        List<Integer> list2 = Arrays.asList(4, 5, 6);
        List<Integer> list3 = Arrays.asList(7, 8, 9);

        Stream<List<Integer>> stream = Stream.of(list1, list2, list3);

        // Use flatMap() to flatten the lists into a single stream of elements
        Stream<Integer> flatMappedStream = stream.flatMap(List::stream);

        // Print the flattened elements
        flatMappedStream.forEach(System.out::println);
    }
}

Output:

1
2
3
4
5
6
7
8
9

Using flatMap() with Nested Structures

This example shows how to use flatMap() to process nested structures, such as a list of sentences, where each sentence is a list of words.

Example

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

public class FlatMapNestedExample {
    public static void main(String[] args) {
        List<String> sentence1 = Arrays.asList("Hello", "world");
        List<String> sentence2 = Arrays.asList("How", "are", "you");
        List<String> sentence3 = Arrays.asList("I", "am", "fine");

        Stream<List<String>> sentences = Stream.of(sentence1, sentence2, sentence3);

        // Use flatMap() to flatten the sentences into a single stream of words
        Stream<String> flatMappedStream = sentences.flatMap(List::stream);

        // Print the flattened words
        flatMappedStream.forEach(System.out::println);
    }
}

Output:

Hello
world
How
are
you
I
am
fine

Real-World Use Case

Flattening a List of Lists of Employees

In real-world applications, the flatMap() method can be used to flatten a list of lists of employees into a single stream of employees.

Example

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

public class FlatMapEmployeeExample {
    static class Employee {
        String name;

        Employee(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    public static void main(String[] args) {
        List<Employee> department1 = Arrays.asList(new Employee("Alice"), new Employee("Bob"));
        List<Employee> department2 = Arrays.asList(new Employee("Charlie"), new Employee("David"));
        List<Employee> department3 = Arrays.asList(new Employee("Eve"), new Employee("Frank"));

        Stream<List<Employee>> departments = Stream.of(department1, department2, department3);

        // Use flatMap() to flatten the departments into a single stream of employees
        Stream<Employee> flatMappedStream = departments.flatMap(List::stream);

        // Print the employees
        flatMappedStream.forEach(System.out::println);
    }
}

Output:

Alice
Bob
Charlie
David
Eve
Frank

Conclusion

The Stream.flatMap() method is used to transform each element of the stream into a new stream and then flatten these streams into a single stream. This method is particularly useful for handling nested structures or generating multiple results for each input element.

By understanding and using this method, you can efficiently manage and process streams of values in your Java applications, transforming and flattening complex data structures as needed.

Leave a Comment

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

Scroll to Top