问题
I have an ArrayList
and I want to iterate over it each 2 elements, like this: ([1,2], [3, 4], [5, 6])
Currently I'm able to iterate the list like this: ([1,2], [2, 3], [3, 4]) but this is not the result I want.
Here is my code:
Iterator<MyObject> iterator = myList.iterator();
if (iterator.hasNext()) {
MyObject o1 = iterator.next();
while (iterator.hasNext()) {
final MyObject o2 = iterator.next();
//Do my stuff
o1 = o2;
}
}
I know that should be quite simple but I don't see it.
I got the code from this link: Link 1
I've also seen these post:
Link 2
Link 3
回答1:
Try this:
for(int i = 0; i < list.size(); i+=2) {
list.get(i);
list.get(i+1);
}
In that you have to check if you don't go over size of list.
来源:https://stackoverflow.com/questions/39013755/java-iterate-over-list-in-pairs-each-2-elements