Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get aggregated list of properties from list of Objects(Java 8)

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.

like image 732
raviraja Avatar asked Oct 18 '25 00:10

raviraja


2 Answers

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());
like image 199
Ravindra Ranwala Avatar answered Oct 20 '25 13:10

Ravindra Ranwala


You can either map the values:

divisions.stream().map(Division::getSections).forEach(sections::addAll);

or simply:

divisions.forEach(d -> sections.addAll(d.getSections()));

like image 45
George Z. Avatar answered Oct 20 '25 13:10

George Z.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!