How to convert List of Lists into List using Java 8

In this post, We will see How to convert List of Lists into List using Java 8. For example, we want to convert List of List of String into List of String or let’s say List of List of Integers to List of Integer.

We can use the Stream flatMap() method to perform this operation.

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

public class ConvertListOfListToList {
    public static void main(String[] args) {
        List<String> stringList1 = Arrays.asList("One", "two");
        List<String> stringList2 = Arrays.asList("three", "four");
        List<String> stringList3 = Arrays.asList("five", "six");

        List<List<String>> listOfListOfString = new ArrayList<>();
        listOfListOfString.add(stringList1);
        listOfListOfString.add(stringList2);
        listOfListOfString.add(stringList3);

        List<String> finalList = listOfListOfString.stream()
                .flatMap(List::stream).collect(Collectors.toList());

        finalList.forEach(str -> {
            System.out.println(str);
        });
    }
}

Summary – In this quick post we have seen How to convert List of Lists into List using Java 8.