简体   繁体   中英

Sum of array list using class with multiple elements java

I have a class like this

public class SellableItems {
    private int id;
    private String name;
    private double price;

    public SellableItems() {
    }

    }
    // getters and setters here
}

Now lets say I have created some objects and put them into an ArrayList , which looks like this

List<SellableItems> table1 = Main.readFromTable1();

Then goes my question. How do calculate the sum (the price) of the ArrayList ?

If you are using Java 8, you can do it very easily with streams:

List<SellAbleItems> table1 = Main.readFromTable1();

double sum = table1.stream().mapToDouble(e -> e.getPrice()).sum();
// use your sum

You'll need to reduce the list to a double value, to do so, you have to iterate over the Table1 and in each iteration add the price value to the sum variable:

double sum = 0d;
for(SellAbleItems s : Table1) 
     sum += s.getPrice();

If your List is a list of Integers you can use something like:

int sum = 0;
for (int ListItm : DataList) {
    sum += ListItm;
}

Otherwise apply necessary adaptations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM