One line to do it using Java streams:
public int calculateSum(List<Product> products) {
return products.stream().mapToInt(Product::getPrice).sum()
}
The explanation:
.mapToInt(Product::getPrice)
, is the equivalent of mapToInt(p -> p.getPrice())
. Basically, from the list of products, we retrieve their prices, and end up having a stream of numbers (prices).
.sum()
will just calculate the sum of integers that are within the stream, in this case a list of prices.
If you want to do it without streams, here's the code for that:
public int calculateSum(List<Product> products) {
int sum = 0;
for (Product product : products) {
sum += product.getPrice();
}
return sum;
}
I've assumed the Product
class looks like the following:
public class Product {
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}