Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current value of an ArrayList - Java

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.

like image 321
egx Avatar asked May 11 '26 07:05

egx


2 Answers

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);
}
like image 158
Joakim Danielson Avatar answered May 12 '26 20:05

Joakim Danielson


To solve the problem you need to first start iterating at index 0 and not 1. Then what you can do is only calculate the sum of previous if the current index is greater than zero. You can calculate the sum of the previous by iterating over all previous elements and adding the sum of them.

        ArrayList<Double> list = new ArrayList<>(Arrays.asList(10.0, 10.0, 10.0, 10.0, 10.0));

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

        for (int index = 0; index  < list.size(); index++) {
            double previousSum = index == 0 ? 0 : IntStream.range(0, index)
                    .mapToDouble(list::get).sum();

            double valueAtIndex = list.get(index);

            sums.add(previousSum + valueAtIndex);
        }

Outut

[10.0, 20.0, 30.0, 40.0, 50.0]
like image 26
Jason Avatar answered May 12 '26 20:05

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!