How to get a flat List of elements that belongs to elements in a List using Java Stream

Viewed 74

I'm trying to get a List of Components that belongs to a given List of Projects.

Since I'm starting working with stream, I cannot figure out how to do this.

 projects.stream()
         .map(p -> p.getComponents())
         .collect(Collectors.toList());

Since Project.getComponents() returns a Collection<ProjectComponent> the previous code will return a List<Collection<ProjectComponent>> however I wanted to return a List<ProjectComponent> how can I do this?

Kind Regards.

1 Answers

use flatMap

projects.stream()
        .flatMap(p -> p.getComponents().stream())
        .collect(Collectors.toList());

flatMap will essentially flatten the nested streams i.e from Stream<Stream<R>> to Stream<R> in which case you then collect the streams elements into a List<ProjectComponent>.

Related