Get the current value of an ArraList - Java

egx :

I want to get the current value of an ArrayList. In other words, I want to loop through my list and get the current value of the instance the loop runs through + all the previous values. Here are my list:

ArrayList<Double> list = new ArrayList<>(); 
list.add(10.0);
list.add(10.0);
list.add(10.0);
list.add(10.0);
list.add(10.0);

I have looped through it like this:

ArrayList<Double> list1 = new ArrayList<>(); 

for (int i = 1; i < list.size(); i++) {
     list1.add(list.get(i) + list.get(i - 1));
}

System.out.print(list1);

My problem is of course that I only get the current value + the previous value. But I want to get the current value + ALL the previous values so the ArrayList "list1" consist of [10, 20, 30, 40, 50] and NOT [20, 20, 20, 20, 20] which is now the case.

I'm still learning so I know that there is probably a simple/basic way of doing this, but I've unfortunately not been able to come up with a solution on my own.

Joakim Danielson :

You want to use a variable for adding the value and then adding that to the list

double sum = 0;
for (int i = 0; i < list.size(); i++) {
    sum += list.get(i);
    list1.add(sum);
}

If you want the whole array then using a for each loop is better.

double sum = 0;
for (Double value: list) {
    sum += value;
    list1.add(sum);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18586&siteId=1