How to collect multiple lists to one list with java-streams?
25,852
You can collect the Lists contained in the MyListService
instances with flatMap
:
List<MyObject> list = services.stream()
.flatMap(s -> s.getObjects().stream())
.collect(Collectors.toList());
Related videos on Youtube
Author by
membersound
JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.
Updated on January 25, 2020Comments
-
membersound over 4 years
How can I collect multiple
List
values into one list, usingjava-streams
?List<MyListService> services; services.stream().XXX.collect(Collectors.toList()); interface MyListService { List<MyObject> getObjects(); }
As I have full control over the interface: or should I change the method to return an Array instead of a List?
-
Eran almost 8 yearsThat depends on what
MyListService
is and how you obtain List[s] from instances of it. -
Mureinik almost 8 yearsWhat exactly is
MyListService
? Can you share its public methods please? How should the result look? -
membersound almost 8 yearsThe service may contain any method that returns a list of objects
-
-
membersound almost 8 yearsGreat that works, if it's the preferred way.
-
Eran almost 8 years@membersound That's what
flatMap
exists for. -
wheelerswebservices over 6 yearsOmg thanks this saved me from creating extra lists and moving them all 1 by 1 with a For Each