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

I have an Item[] items that contains some basic statistics about myself.

 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 getAttackDamage() over the elements of my characters and apply their getAttackDamage() to the return result.

Is there a way to rewrite this instead of using lambda expressions? I tried the following:

 public float getAttackDamage() { float bonus = 0; Arrays.stream(items).forEach(i -> bonus += i.getAttackDamage()); return baseAttackDamage + attackDamageScaling * level + bonus; } 

But this did not work (compiler error). Is it possible?

+5
source share
1 answer

Yes, you may 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. This disrupts functional programming (see Brian Goetz's comment ). This code creates a stream of each of your element. Non-empty elements are filtered and displayed in double value, corresponding to damage to the attack.

+7
source

Source: https://habr.com/ru/post/1236503/


All Articles