How to get the product of two properties from a list of objects in Java 8

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.

Answer

Calculate the product using map and then get the sum with reduce:

list.stream()
    .map(p -> p.getPrice().multiply(p.getQty()))
    .reduce(BigDecimal.ZERO, BigDecimal::add);

Leave a Reply

Your email address will not be published. Required fields are marked *