javaarraylist

Iterate over consecutive object pairs in an ArrayList


I want to get pairs of objects from an ArrayList so I can perform calculations between the elements of each object. Ideally it should iterate over pairs of objects. For example in a List with {obj1, obj2, obj3, obj4} it should go over {obj1, obj2}, {obj2, obj3} and {obj3, obj4}.

What I have tried so far is as follows.

public class Sum {
    public ArrayList<Double> calculateSum(ArrayList<Iter> iter) {
        ListIterator<Iter> it = iter.listIterator();
        ArrayList<Double> sums = new ArrayList<>();
        
        while (it.hasNext()) {
            Iter it1 = it.next();
            Iter it2;
            if(it.hasNext()){
                it2 = it.next();
            } else {    break;  }
            
            double sum = it1.getValue() + it2.getValue();
            sums.add(sum);
        }
        return sums;
    }
}

Here, it just iterates as {obj1, obj2} and {obj3, obj4}. How can I fix this?


Solution

  • A very normal loop, except that you need to loop up to list.size() - 1, the before last element of the array.

    public ArrayList<Double> calculateSum(ArrayList<Iter> list) {
        ArrayList<Double> sums = new ArrayList<>();
    
        for (int i = 0; i < list.size() - 1; i++) {
            double sum = list.get(i).getValue() + list.get(i + 1).getValue();
            sums.add(sum);
        }
        return sums;
    }
    

    EDIT

    Using an iterator in this case will not be faster than doing a normal loop and just makes the logic unnecessarily complicated and can easily introduce bugs.