Reputation: 1243
I have an Item[] items
which contains some basic stats about itself.
public float getAttackDamage() {
float bonus = 0;
for(int i = 0 ; i < items.length; i++){
if(items[i] != null){
bonus += items[i].getAttackDamage();
}
}
return baseAttackDamage + attackDamageScaling * level + bonus;
}
The above code is how I currently loop through my characters items and apply their getAttackDamage()
to the return result.
Is there a way I can rewrite this to use a lambda expressions instead? I tried the follow:
public float getAttackDamage() {
float bonus = 0;
Arrays.stream(items).forEach(i -> bonus += i.getAttackDamage());
return baseAttackDamage + attackDamageScaling * level + bonus;
}
But it didn't work (compiler error). Is this possible?
Upvotes: 6
Views: 2904
Reputation: 137064
Yes, you could have the following:
double bonus = Arrays.stream(items)
.filter(Objects::nonNull)
.mapToDouble(Item::getAttackDamage)
.sum();
You should remember that forEach
is probably not the method you want to call. It breaks functional programming (refer to Brian Goetz's comment). In this code, a Stream of each of your item is created. The non-null elements are filtered and mapped to a double value corresponding to the attack damage.
Upvotes: 11