Looping ArrayList in Java or Iteration over ArrayList is very similar to looping Map in Java. In order to loop ArrayList in Java we can use either foreach loop, simple for loop or Java Iterator from ArrayList. We have already touched iterating ArrayList in 10 Example of ArrayList in Java and we will see here in detail. We are going to see examples of all three approaches in this ArrayList tutorial and find out which one is clean and best method of looping arraylist in Java. Before start writing an example for loop in ArrayList let's think why do we need to iterate, traverse or loop an ArrayList if it’s based on index and backed by Array. If we know the index of element than we can directly get that particular element from ArrayList but if you want to print all elements of arraylist and do some operation one by one on each of them, only looping or traversing will help you.
This article is in continuation of my earlier tutorial on ArrayList e.g. How to sort ArrayList in Java on descending order and How to convert Array to ArrayList in Java. If you haven’t read them already then you may find them useful and interesting.
How to Loop, Iterate or traverse Arraylist in Java - Code Example
Essentially there are four ways to iterate, traverse of loop ArrayList in Java:
1) Looping using Java5 foreach loop.
2) Looping ArrayList using for loop and size() method.
3) Iterating ArrayList using Iterator.
4) Traversing ArrayList using ListIterator in Java.
Looping ArrayList with foreach loop on Java 5
We can iterate on Java ArrayList using foreach loop introduced in Java 5, by far most clean method until you don't need to remove elements from ArrayList in that case you must user Java Iterator for looping or iterating over ArrayList. Since ArrayList provides size() method you can also use plain old for(int i; i<size; i++) loop also for iterating or traversing ArrayList in Java. See example section post for complete code example of looping ArrayList in Java.
Iterating ArrayList in Java using Iterator and while loop
Another cool approach of looping ArrayList is using Iterator in combination of while loop and traverse until you get to the end of ArrayList. Iterator has a method hasNext() which will return true until there is an element in Iterator. Always call hasNext() before calling next() method on Iterator to avoid java.util.NoSuchElementException. Also by using Iterator approach for looping ArrayList you can remove element from ArrayList without fear of ConcurrentModificationException. See below for full code example of looping ArrayList in Java.
That’s all on four example to loop ArrayList in Java. We have seen foreach loop, Iterator and other approaches for traversing ArayList and in my opinion foreach loop rules for simple iteration and Iterator rules if you need to remove elements from ArrayList during iteration.ListIterator also offers add() method to add new elements in ArrayList while looping.
Other Java Collection tutorial you may like