Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect list of filterred objects from sub-collections

Let's have data structure, which is described below.

Class LandResearch {
    Research research;
}

Class Research {
    List<Bonus> bonuses;
}

Class Bonus {
    BonusType bonusType;
    double bonusValue;
}

I'am in situation, when I have a List<LandResearch> and I have specific BonusType. I want collect all bonuses, which has given BonusType.

It is not problem do it with for cycles, but I would like to manage it with streams.

Existing solution, which I would like to replace.

List<Bonus> bonuses = new ArrayList<>();
for (LandResearch landResearch: landResearches) {
    for (Bonus bonus: landResearch.getResearch().getBonuses()){
        if (bonus.getBonusType().equals(searchedBonusType)){
            bonuses.add(bonus);
        }
    }
}

Thank you for help and hints.

like image 669
Kariton Avatar asked Jan 01 '23 23:01

Kariton


1 Answers

Use flatMap to produce a Stream of all the Bonus instances, then filter and collect to a List:

List<Bonus> bonuses =
    landResearches.stream() // Stream<LandResearch>
                  .flatMap(l->l.getResearch().getBonuses().stream()) // Stream<Bonus>
                  .filter(b->b.getBonusType().equals(searchedBonusType)) // Stream<Bonus>
                  .collect(Collectors.toList()); // List<Bonus>
like image 157
Eran Avatar answered Jan 05 '23 06:01

Eran