Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Working with Nested Structures with the flatMap() Method | Intermediate Operations in Stream API
Stream API
course content

Course Content

Stream API

Stream API

1. Fundamentals and Functional Capabilities of Stream API
4. Practical Applications of Stream API

book
Working with Nested Structures with the flatMap() Method

When working with data collections in Java, you often encounter situations where our structures are nested. For example, you might have a list of objects, each containing another list of objects.

In such cases, standard operations like map() are not suitable for extracting all nested data in a single stream. This is where the flatMap() method from the Stream API comes in.

The flatMap() method takes a function that transforms each element of the stream into a new stream.

  • <R> — the type of elements in the resulting stream;
  • Function<? super T, ? extends Stream<? extends R>> mapper — a function that takes an element from the original stream (T) and returns a stream (Stream<R>) of resulting elements.

It's important to understand that flatMap() does not simply return a new element but rather a stream (or another collection) for each element. These individual streams are then combined into one.

Practical Application

Imagine you have multiple factories, each producing different types of products. Our goal is to create a unified list of all products from these factories and convert their names to uppercase.

java

Main

copy
123456789101112131415161718192021222324252627282930313233343536
package com.example; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Factory> factories = Arrays.asList( new Factory("SteelWorks", Arrays.asList("Drill", "Excavator", "Bulldozer")), new Factory("AutoParts", Arrays.asList("Carburetor", "Piston", "Transmission")), new Factory("ToolMakers", Arrays.asList("Screwdriver", "Wrench", "Hammer")) ); List<String> productList = factories.stream() .flatMap(factory -> factory.getProducts().stream()) // Flatten all product lists into a single stream .map(String::toUpperCase) // Convert product names to uppercase .toList(); // Collect results into a list System.out.println(productList); } } class Factory { private String name; private List<String> products; public Factory(String name, List<String> products) { this.name = name; this.products = products; } public List<String> getProducts() { return products; } }

The factories list contains multiple Factory objects, each holding a name and a list of products. Since getProducts() returns a list, calling stream() on factories would normally give us a stream of Factory objects, which isn't what we need.

To extract the actual product names, you use flatMap(factory -> factory.getProducts().stream()). This flattens all product lists into a single continuous stream of String values.

Then, map(String::toUpperCase) applies the toUpperCase() method to each product name, ensuring all names are in uppercase before collecting them into productList using toList().

Merging Collections into One

When data is organized as nested collections, the flatMap() method helps merge them into a single stream, making further processing easier. For example, you can combine an array that contains other arrays into a single array.

Example

You have multiple production lines, each manufacturing several products. Our goal is to get a single list of all products produced across these lines.

java

Main

copy
12345678910111213141516171819202122
package com.example; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { // List of production lines with their products List<List<String>> productionLines = Arrays.asList( Arrays.asList("Tire", "Rim", "Shock Absorber"), Arrays.asList("Frame", "Tread", "Ball Joint"), Arrays.asList("Brakes", "Steering System") ); // Get a single list of all products manufactured in the factory List<String> allProducts = productionLines.stream() .flatMap(line -> line.stream()) // Convert each production line's product list into a stream .toList(); // Collect all products into a single list System.out.println(allProducts); } }

This code uses flatMap() to merge nested lists of products from different production lines into a single unified stream.

Each production line, represented as a list of products, is converted into a stream of elements, which is then collected into a final list using toList(). As a result, you get a single list containing all products manufactured in the factory.

1. What does the flatMap() method do in the Stream API?

2. What happens when using flatMap() with nested collections?

question mark

What does the flatMap() method do in the Stream API?

Select the correct answer

question mark

What happens when using flatMap() with nested collections?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 4
We're sorry to hear that something went wrong. What happened?
some-alt