0

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?

2
  • Just a note, it's the recommended format to not start variable names with capital letters as you do with Table1. As you can see, even the SO thinks it's a type and is highlighting it teal. Commented Apr 15, 2018 at 19:44
  • Yes, you are absolutely right. I have updated my question, thanks! Commented Apr 30, 2020 at 22:17

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();

2 Comments

So this is just a foreach loop and adding all the entries together to the double sum?
@PeterHoldensgaard yes.
1

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

2 Comments

@PeterHoldensgaard please consider accepting this answer then. It is 1:1 the same as the one you accepted but it was posted an hour earlier
Works like a charm, thanks! Assuming that I did this using a string as sum, could I then print out all the names from table1?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.