27

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. Commented Jun 6, 2016 at 7:55
  • What exactly is MyListService? Can you share its public methods please? How should the result look? Commented Jun 6, 2016 at 7:58
  • The service may contain any method that returns a list of objects Commented Jun 6, 2016 at 8:02

1 Answer 1

62

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());
Sign up to request clarification or add additional context in comments.

3 Comments

Great that works, if it's the preferred way.
@membersound That's what flatMap exists for.
Omg thanks this saved me from creating extra lists and moving them all 1 by 1 with a For Each

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.