26

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?

3
  • That depends on what MyListService is and how you obtain List[s] from instances of it.
    – Eran
    Jun 6, 2016 at 7:55
  • What exactly is MyListService? Can you share its public methods please? How should the result look?
    – Mureinik
    Jun 6, 2016 at 7:58
  • The service may contain any method that returns a list of objects Jun 6, 2016 at 8:02

1 Answer 1

59

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());
3
  • Great that works, if it's the preferred way. Jun 6, 2016 at 8:03
  • 6
    @membersound That's what flatMap exists for.
    – Eran
    Jun 6, 2016 at 8:06
  • Omg thanks this saved me from creating extra lists and moving them all 1 by 1 with a For Each Sep 8, 2017 at 21:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.