Shaun Wild
Shaun Wild

Reputation: 1243

Can I use a lambda expression to accumulate the sum in the variable?

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

Answers (1)

Tunaki
Tunaki

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

Related Questions