Java Iterate over List in pairs each 2 elements [duplicate]

纵饮孤独 提交于 2020-12-27 07:23:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!