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
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();
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