25

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
  • 74,158
  • 163
  • 522
  • 986

1 Answers1

56

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
  • 74,158
  • 163
  • 522
  • 986
Eran
  • 374,785
  • 51
  • 663
  • 734