问题
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?
All help is greatly appreciated. Thanks!
回答1:
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.
回答2:
A little modification to Davide's answer
for (int i = 0; i < list.size() - 1; i ++) {
sums.add(list.get(i) + list.get(i+1));
}
Because the OP wanted {obj1, obj2} {obj2, obj3} ...etc
Using a iterator
itr = list.iterator();
while(itr.hasNext()) {
Double x = itr.next();
if(itr.hasNext()){
x+= itr.next();
sum.add(x);}
itr.previous();
}
This is not recommended.
回答3:
Simply use a for loop and stop at element before last one.
for (int i = 0; i < iter.size() - 1; i++) {
Iter first = iter.get(i);
Iter second = iter.get(i + 1);
// Your code here
}
回答4:
public static ArrayList<Double> calculateSum(ArrayList<Iter> iter) {
ListIterator<Iter> it = iter.listIterator();
ArrayList<Double> sums = new ArrayList<>();
if (it.hasNext()) {
double prev = it.next().getValue();
while (it.hasNext()) {
double current = it.next().getValue();
double sum = prev + current;
sums.add(sum);
prev = current;
}
}
return sums;
}
回答5:
Try this :-
public ArrayList<Double> calculateSum(ArrayList<Iter> inputList) {
ArrayList<Double> sums = new ArrayList<Double>();
int inputSize = inputList.size(); // size should be saved as an int , instead of calling size() over the list again and again in for loop
int incVar = 1; // 1 incremented value
double sum = 0.0d;
for(int i = 0; incVar < inputSize; i++,incVar++){
sum = inputList.get(i).getValue() + inputList.get(incVar).getValue();
sums.add(sum);
}
return sums;
}
来源:https://stackoverflow.com/questions/31222023/iterate-over-consecutive-object-pairs-in-an-arraylist