Curious Mind
Curious Mind

Reputation: 659

Java stream multiply and return sum of multiplication

Currently I am using a for loop to perform a simple multiplication and sum the obtained values:

BigDecimal serviceOrderTotal = new BigDecimal(0.00);
for (int i = 0; i < orderPresenter.getServiceList().size(); i++) {
    System.out.println("orderPresenter.getServiceList().get(i).getServiceValue()");
    System.out.println(orderPresenter.getServiceList().get(i).getServiceValue());
    System.out.println("orderPresenter.getServiceList().get(i).getServiceQuantity()");
    System.out.println(orderPresenter.getServiceList().get(i).getServiceQuantity());
    serviceOrderTotalold = serviceOrderTotal.add(orderPresenter.getServiceList().get(i).getServiceValue().multiply(orderPresenter.getServiceList().get(i).getServiceQuantity()));
}

I need to do the same using streams. For each of the orderPresenters, I need to multiply value for the quantity and return the sum of those values.

If I do it using a forEach in the stream, I cannot return the value cause the variable must be final or atomic to be used inside the forEach. I ended up with this to no avail:

BigDecimal serviceOrderTotal = new BigDecimal(0.00);
serviceOrderTotal = orderPresenter.getServiceList().stream()
               .forEach(servicePresenter -> {
                    System.out.println("orderPresenter.getServiceValue()");
                    System.out.println(orderPresenter.getServiceValue());
                    System.out.println("orderPresenter.getServiceQuantity()");
                    System.out.println(orderPresenter.getServiceQuantity());
                    serviceOrderTotalold = serviceOrderTotalold.add(orderPresenter.getServiceValue().multiply(orderPresenter.getServiceQuantity()));
                });

Upvotes: 4

Views: 3597

Answers (2)

WJS
WJS

Reputation: 40034

Once you get the list, do this. Not certain what your List looks like.

BigDecimal sum = list.stream()
                     .map(sv -> sv.getServiceValue().multiply(sv.getServiceQuantity()))
                     .reduce(new BigDecimal(0.0), (a, b) -> a.add(b));

Upvotes: 2

Naman
Naman

Reputation: 31878

You can modify your implementation to use a foreach such as:

BigDecimal serviceOrderTotal = BigDecimal.ZERO;
for (Service service : orderPresenter.getServiceList()) {
    serviceOrderTotal = serviceOrderTotal.add(service.getServiceValue().multiply(service.getServiceQuantity()));
}

This can also be transformed using the map and reduce operations of java-stream further as:

BigDecimal serviceOrderTotal = orderPresenter.getServiceList().stream()
        .map(service -> service.getServiceValue().multiply(service.getServiceQuantity()))
        .reduce(BigDecimal.ZERO, BigDecimal::add);

Upvotes: 6

Related Questions