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;

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<>();

        List<String> jcdFlatMapList =
                                             .flatMap(widgetList ->
        System.out.println("Widget List:");




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 *