Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulate inside forEach Java 8

Tags:

java

java-8

How can I accumulate inside a forEach? this is my code:

public Double accumulate() {
        Double accum = 0d;

        numbers.stream().forEach(p-> {

            // if condition
                accum = accum + numbers.getAmount();
            // else
                accum = accum + numbers.getAmountWithInterest();
        });

        return accum;
    }

Maybe I should use map instead of forEach, I tried a couple of things but it didn't work. Thanks

like image 324
Julio Avatar asked Dec 18 '22 12:12

Julio


1 Answers

I do not think it is a good idea to make side effect when using lambda. It is a bad way of mixing functional and imperative programming. You can do it easier by

numbers.stream().mapToInt(p-> {
    // if condition
        return numbers.getAmount();
    // else
        return numbers.getAmountWithInterest();
}).sum();
like image 109
HamoriZ Avatar answered Feb 08 '23 17:02

HamoriZ