Nick P Nick P - 6 months ago 28
Java Question

Java Stream- Add two columns and sum results

I have a Price object that has two attributes, cost and tax. I want to be able to stream over a list of Price Objects, add the cost and tax together, and then sum up the total.

Is there a way to do this entirely in a Java 8 stream? I am thinking of logic along the lines of this:

List<Price> prices = Price.find.all();
Double sum = 0.0;
prices.stream().forEach(price -> { sum = sum + price.cost + price.tax });

Answer
double total = prices.stream()
                     .mapToDouble(price -> price.cost + price.tax)
                     .sum();

As simple as that.

Comments