raviraja :
I have a class Division
which is having a list of Section
as property as below
class Division {
private List<Section> sections;
// respective getters and setters
}
Let's say I have a list of divisions, and I want to get an aggregated list of Sections, I know it can be done using the regular approach as below.
List<Division> divisions = getDivisions();
List<Section> sections = new ArrayList<>();
for (Division division : divisions) {
sections.addAll(division.getSections());
}
I want to know if there is any way of doing the same using Java-8 streams.
Ravindra Ranwala :
You may do it using the flatMap
operator. Here's how it looks.
List<Section> sections = divisions.stream()
.flatMap(d -> d.getSections().stream())
.collect(Collectors.toList());