I have a list of objects with price and quantity. And I am looking to get the total sum, which is the sum of all (product price * product qty) in the list of objects. What’s the best way to do this is in Java 8?
I could get the sum of all product prices by streaming list with
list..stream().map(Product::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add)); but what I am not sure is how to get the product of price and quantity as well.
Calculate the product using
map and then get the sum with
list.stream() .map(p -> p.getPrice().multiply(p.getQty())) .reduce(BigDecimal.ZERO, BigDecimal::add);