Let's imagine I have this class:
public class Borrow {
private Float perCent;
private Float rate;
}
and I have a list of Borrow
objects:
List<Borrow> moneyBorrowed = new ArrayList<Borrow>();
For each Borrow
element, I need to multiply perCent
by rate
and sum all the results.
I want to use a lambda expression in Java 8. I want to use something like this:
moneyBorrowed.stream().forEach(p -> {
p.getPerCent() * p.getRate()
}).sum();
but I am not having much luck...
Any suggestion?
Instead of forEach
, you need to use one of the mapXxx
methods. In you case, you can use mapToDouble
(there is no mapToFloat
method):
double sum = moneyBorrowed.stream().mapToDouble(p -> p.getPerCent() * p.getRate()).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