user3287300
user3287300

Reputation: 151

Adding elements in an ArrayList together

If I have an ArrayList like:

[20,5,7,9]

and I want to add 20+5 and 7+9 and create a new value to replace the two I added together so I would create a new ArrayList like:

[25,16]

How would I go about doing this? Would I just create an int result and declare a new ArrayList, then replace the values into the new ArrayList? Or can I just edit the ArrayList as it computes the value?

Upvotes: 0

Views: 1163

Answers (4)

Zini
Zini

Reputation: 914

 public static void main(String []args){
List<Integer> list = new ArrayList<Integer>(Arrays.asList(20, 5, 7, 9));
List<Integer> list2 = new ArrayList<Integer>();

for(int i=0; i< list.size(); i++){
  if (i % 2 == 1) {
    continue;
  }
  list2.add(list.get(i) + (list.size() > i + 1 ? list.get(i+1) : 0 ));
}
for(Integer it :  list2) {            
    System.out.println(it);
}

 }

}

Upvotes: 1

SS781
SS781

Reputation: 2649

I would try the following:

...
List<Integer> result = new ArrayList<Integer>();
try{
    for (int i=0; i<source.size();i=i+2)
        result.add(source.get(i)+source.get(i+1));
    }
catch (IndexOutOfBoundsException e){
    }

(assuming 'source' is your original list)

Let me know if this helps!

Upvotes: 1

aliteralmind
aliteralmind

Reputation: 20163

You can do it right in the original ArrayList:

Pseudo-code:

for(the next two elements)
   get the sum
   set the first element to the sum
   delete the second       

Code:

for(int i = 0; i < (list.size() - 1); i++)  {
   int sum = list.get(i) + list.get(i + 1);
   list.set(i, sum);
   list.remove(i + 1);

   //i is incremented by ONE, because the element 
   //after i was just deleted.
}

Upvotes: 1

user3487224
user3487224

Reputation: 1

I would create new array and put the new value into the array. I think this way is better. To add 20 to 5 you just call out the first element and add to the second element and then put it into your new array. Do the same for the 7+9, the key is that make sure you call out the right element.

Upvotes: 0

Related Questions