Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
Shaun Wild Avatar asked Nov 21 '15 16:11

Shaun Wild


People also ask

Can a lambda be put in a variable?

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.

What can you use a lambda expression for?

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.

Can lambda expressions create functions as data?

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.

How do you add two numbers using lambda expression?

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.


1 Answers

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.

like image 110
Tunaki Avatar answered Oct 21 '22 23:10

Tunaki