Several operations in the list of complex objects with lambda

Suppose I have this class:

public class Borrow {
   private Float perCent;
   private Float rate;
}

and I have a list of objects Borrow:

List<Borrow> moneyBorrowed = new ArrayList<Borrow>();

For each element, BorrowI need to multiply perCentby rateand summarize 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โ€™m not very lucky ...

Any suggestion?

+4
source share
2 answers

Instead, forEachyou need to use one of the methods mapXxx. In this case, you can use mapToDouble(no method mapToFloat):

double sum = moneyBorrowed.stream().mapToDouble(p -> p.getPerCent() * p.getRate()).sum();
+6
source

forEach is a terminal operation that does not have a return value, so you cannot associate a method call with it.

mapToDouble Stream DoubleStream, :

double sum = moneyBorrowed.stream().mapToDouble(p -> p.getPerCent() * p.getRate()).sum();
+6

Source: https://habr.com/ru/post/1693631/


All Articles