Kariton
Kariton

Reputation: 225

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.

Upvotes: 4

Views: 89

Answers (2)

Frank Neblung
Frank Neblung

Reputation: 3175

In the case that kotlin is an option for you

private fun Collection<LandResearch>.bonuses(wanted: BonusType): List<Bonus> =
        flatMap { it.research.bonuses }.filter { it.bonusType == wanted }

Use it like this:

val bonusesOfWantedType = listOfLandSearches.bonuses(wantedBonusType)

Upvotes: 0

Eran
Eran

Reputation: 393936

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>

Upvotes: 9

Related Questions