Java Stream flatMap() Example

1. Introduction

The flatMap() method in Java Streams is used to flatten complex structures into simpler and more usable forms. This method is particularly useful when working with streams of arrays, collections, or any structures that contain nested elements. It combines elements from these nested structures into a single stream, making it easier to perform further operations without dealing with complexity.

Key Points

1. flatMap() converts each element of the stream into another stream and then concatenates these streams into a single stream.

2. This method is essential for handling nested collections or arrays effectively within a stream.

3. It is often used in conjunction with map() for comprehensive data transformation tasks.

2. Program Steps

1. Import necessary classes.

2. Create a list of lists (or any nested structure).

3. Apply the flatMap() method to flatten the structure.

4. Use a terminal operation to collect and display the results.

3. Code Program

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

public class StreamFlatMapExample {

    public static void main(String[] args) {
        // Step 2: Create a list of lists
        List<List<String>> listOfLists = Arrays.asList(
            Arrays.asList("Apple", "Banana"),
            Arrays.asList("Carrot", "Daikon"),
            Arrays.asList("Eggplant", "Fig")
        );

        // Step 3: Apply flatMap to flatten the nested lists
        List<String> flatList = listOfLists.stream()
                                           .flatMap(List::stream)
                                           .collect(Collectors.toList());

        // Step 4: Use forEach to output the results
        System.out.println("Flattened list:");
        flatList.forEach(System.out::println);
    }
}

Output:

Flattened list:
Apple
Banana
Carrot
Daikon
Eggplant
Fig

Explanation:

1. Setup and Data Structure: The program begins by setting up a list of lists containing strings. Each sublist represents a collection of items.

2. Using flatMap(): The flatMap(List::stream) method is applied to each element (which itself is a list) of the main list. This operation effectively flattens the lists into a single stream of strings, eliminating the nested structure.

3. Collecting and Outputting Results: The flattened stream is then collected into a single list of strings using Collectors.toList(). Finally, the contents of the flattened list are printed out, showcasing all items from the nested lists in a single, unified format.

4. Utility of flatMap(): This example illustrates how flatMap() simplifies handling of nested collections by converting them into a more manageable form, which is particularly useful for complex data transformations and stream operations that require a uniform input format.


Comments