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.
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>
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