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.
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());
You can either map the values:
divisions.stream().map(Division::getSections).forEach(sections::addAll);
or simply:
divisions.forEach(d -> sections.addAll(d.getSections()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With