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());
Share:
25,852

Related videos on Youtube

membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on January 25, 2020

Comments

  • membersound
    membersound over 4 years

    How can I collect multiple List values into one list, using java-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
      Eran almost 8 years
      That depends on what MyListService is and how you obtain List[s] from instances of it.
    • Mureinik
      Mureinik almost 8 years
      What exactly is MyListService? Can you share its public methods please? How should the result look?
    • membersound
      membersound almost 8 years
      The service may contain any method that returns a list of objects
  • membersound
    membersound almost 8 years
    Great that works, if it's the preferred way.
  • Eran
    Eran almost 8 years
    @membersound That's what flatMap exists for.
  • wheelerswebservices
    wheelerswebservices over 6 years
    Omg thanks this saved me from creating extra lists and moving them all 1 by 1 with a For Each