sfandler sfandler - 2 months ago 14
Java Question

How to merge a nested List into a simple List using Java 8 Stream API

I have a

List
which looks as follows:

List<List<Class2>> list = new ArrayList<>();

List<Class2> l1 = new ArrayList<>();
l1.add(new Class2(new Class3()));
l1.add(new Class2(new Class3()));
l1.add(new Class2(new Class3()));
list.add(l1);

List<Class2> l2 = new ArrayList<>();
l2.add(new Class2(new Class3()));
l2.add(new Class2(new Class3()));
l2.add(new Class2(new Class3()));
list.add(l2);


How can I convert the
List
list
into a
List<Class3>
using the Java 8 Stream API?

Answer

Since you are passing to the Class2 constructor an instance of Class3, I'm assuming Class2 has a Class3 member with a getter (lets call the getter getClass3()).

Based on this assumption, you can do the following to get a List<Class3> of all the Class3 members of all the Class2 members of all the lists contained in list :

List<Class3> listOf3 = 
    list.stream()
        .flatMap(List::stream) // convert a Stream<List<Class2>> to Stream<Class2>
        .map(Class2::getClass3) // convert a Stream<Class2> to Stream<Class3>
        .collect(Collectors.toList()); // collect to a List<Class3>