0

I have a rather simple question since I'm a beginner.

I'm using a Java List class and I'm interested to know how to iterate through it and get all the object properties as a sum of numbers?

For example, I have a Product class with a price property type of int. My list is now filled with a couple of Products. Now I want to iterate through that list and get the sum of all Product prices.

How do I do that? Thank you.

  • I believe your question has already been asked and answered more than once. [Sum all the elements java arraylist](https://stackoverflow.com/questions/16242733/sum-all-the-elements-java-arraylist) – Abra Mar 06 '20 at 12:57

1 Answers1

2

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;
    }
}
Alexandru Somai
  • 1,395
  • 1
  • 7
  • 16
  • Thank you for the reply. I didn't mention that I'm trying to write a method that is going to take a Java List as a parameter and then return the sum of all product prices. Is it possible without using Java streams and just by for loops? How would I access the lists objects in that case? –  Mar 06 '20 at 12:41
  • 1
    I've created a function for that. And sure, I'll update my answer to include the version without Java streams, as well. – Alexandru Somai Mar 06 '20 at 12:44
  • Nice, thank you so much. Tell me just one more thing - getPrice() is the getter method in Product class, right? –  Mar 06 '20 at 12:50