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?
Lambda expressions can be stored in variables if the variable's type is an interface which has only one method. The lambda expression should have the same number of parameters and the same return type as that method.
The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.
lambda expressions are added in Java 8 and provide below functionalities. Enable to treat functionality as a method argument, or code as data. A function that can be created without belonging to any class. A lambda expression can be passed around as if it was an object and executed on demand.
For example, the below-given lambda expression takes two parameters and returns their addition. Based on the type of x and y , the expression will be used differently. If the parameters match to Integer the expression will add the two numbers. If the parameters of type String the expression will concat the two strings.
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.
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