Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple operations in list of complex objects with lambda

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?

like image 792
Jesus Paradinas Avatar asked Dec 14 '22 18:12

Jesus Paradinas


1 Answers

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();
like image 133
assylias Avatar answered Dec 16 '22 07:12

assylias