How can I turn a List of Lists into a List in Java 8?

Sarah Szabo picture Sarah Szabo · Aug 5, 2014 · Viewed 340.7k times · Source

If I have a List<List<Object>>, how can I turn that into a List<Object> that contains all the objects in the same iteration order by using the features of Java 8?

Answer

Eran picture Eran · Aug 5, 2014

You can use flatMap to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:

List<List<Object>> list = ...
List<Object> flat = 
    list.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());