Java 8 Stream flatMap Sample

Java 8 Stream flatMap operation will return a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

In simpler terms, a flatMap() is used to convert a Stream of Stream into a list of values. Another way to say it is that flatMap() will flatten a Stream of Stream of values into just a Stream of values.

The Stream.flatMap() sample code below will flatten a Stream of List (Strings) objects into just a Stream of Strings.

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

public class JavaFlatMapSample {

	public static void main(String[] args) {


		List<String> bigWidgets = Arrays.asList("BigWidgetA", "BigWidgetB", "BigWidgetC");
		List<String> medWidgets = Arrays.asList("MediumWidgetA", "MediumidgetB", "MediumWidgetC");
        List<String> smallWidgets = Arrays.asList("SmallWidgetA", "SmallWidgetB", "SmallWidgetC");

        
        List<List<String>> allWidgets = new ArrayList<>();
        allWidgets.add(bigWidgets);
        allWidgets.add(medWidgets);
        allWidgets.add(smallWidgets);


        List<String> jcdFlatMapList = allWidgets.stream()
                                             .flatMap(widgetList -> widgetList.stream())
                                             .collect(Collectors.toList());
        
        System.out.println("Widget List:");
        System.out.println(jcdFlatMapList);

	}

}

Output:

Widget List:
[BigWidgetA, BigWidgetB, BigWidgetC, MediumWidgetA, MediumidgetB, MediumWidgetC, SmallWidgetA, SmallWidgetB, SmallWidgetC]


I think you will find the Stream.flatMap() operation of Java 8 to be very useful in your everyday Java programming activities.

Add a Comment

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