简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM