Skip to content
Advertisement

Is there a way to go back by one iteration in a for-each loop?

For example, if I were to do…

for (String s : arraylist) {
    // Do something with string
}

If it isn’t possible, is there another method of traversing through some sort of collection class while controlling the iteration counter? I tried looking through the answers to this question but couldn’t think of a way that was clear to me.

Any suggestions are appreciated!

Advertisement

Answer

It depends on what you are trying to do, but you can use a while-loop and increment the index when it’s appropriate:

while(i<limit){
   list.get(i);
   // Do something

   if(someConditionMet){
     i++
   }
}

Or you can use a for-loop without incrementing the index after each iteration:

for (int i = 0; i < 5; ) {
   list.get(i);
   // Do something

    if(someConditionMet){
        i++;
    }
}

Also if the collection implements Iterable, you can use the iterator to iterate over the collection:

List<Integer> list;

Iterator<Integer> iterator = list.iterator();

while(someCondition){
    if(someOtherContion){
        Integer next = iterator.next();
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement