FlatMap in Java 8

Introduction

This article will explain the usages of the Java 8 Stream.flatMap method.

Flatten a List of List

Let's assume we have a list of lists and we have to convert it into a single List. How we will do that using Java 8.

package com.geekscoder.java8;

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

public class FlatMapExample {

    public static void main(String[] args) {
        List innerList1 = Arrays.asList("inner1","inner2","inner3");

        List innerList2 = Arrays.asList("inner4","inner5","inner6");

        List<List> outerList = Arrays.asList(innerList1,innerList2);

        List fllatenList = outerList.stream().flatMap(Collection::stream).collect(Collectors.toList());

        fllatenList.forEach(System.out::println);


    }

}
Output
inner1
inner2
inner3
inner4
inner5
inner6