Java Stream flatmap() Examples

In Java flatmap() is a function in the Stream class that can be used to flatten a Stream of Collections into a single Stream of Objects.

✏️Note: flatmap() is available only since Java 1.8

Example 1: Concat a 2-Dimensional Integer Array into a single 1-Dimentaional Array
import java.util.Arrays;

public class JavaFlatMapExample {

    public static void main(String[] args) {

        Integer[][] array2D = new Integer[][]{{100, 200,300}, {400,500,600}, {700, 800}};
        Stream<Integer[]> streamOf2DArray =;
        Integer[] array1D = streamOf2DArray.flatMap(Stream::of).toArray(Integer[]::new);

Input: [[100, 200, 300], [400, 500, 600], [700, 800]]
Result: [100, 200, 300, 400, 500, 600, 700, 800]

Example 2: Concat a 2-Dimensional String Array into a single 1-Dimentaional Array
    public static void main(String[] args) {

        String[][] array2D = new String[][]{{"one", "two"}, {"three","four","five"}, {"six", "seven","eight","nine","ten"}};
        Stream<String[]> streamOf2DArray =;
        String[] array1D = streamOf2DArray.flatMap(Stream::of).toArray(String[]::new);

Input: [[one, two], [three, four, five], [six, seven, eight, nine, ten]]
Result: [one, two, three, four, five, six, seven, eight, nine, ten]

Java Stream flatmap Examples

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap