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?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

60

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());
membersound
  • 81,582
  • 193
  • 585
  • 1,120
Eran
  • 387,369
  • 54
  • 702
  • 768