Skip to content
Advertisement

Accumulate inside forEach 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

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement