Collections

Java ArrayList Iterate Example

Java ArrayList iterate example shows various ways to iterate through ArrayList. Example also shows how to iterate ArrayList in reverse order.

How to Iterate Java ArrayList?

There are several ways using which you can iterate through elements of Java ArrayList.

1)    Iterate ArrayList using while loop

This is the simplest method to iterate through elements of an ArrayList.

Output

2)    Iterate ArrayList using for loop

Iterate through ArrayList using for loop is straight forward as given below.

Output

3)    Iterate ArrayList using enhanced for loop ( Java 1.5 and above version)

If you are using Java version 1.5 and above, you can use advanced for loop to iterate the ArrayList.

Output

4)    Iterate ArrayList using Iterator

ArrayList provides Iterator object which can be used to iterate through ArrayList using its hashNext() and next() methods.

Output

5)    Iterate ArrayList using ListIterator

ArrayList also provides ListIterator to iterate through its elements. Get ListIterator object of an ArrayList using listIterator() method.

Output

ListIterator also provides hasPrevious() and previous() methods to iterate ArrayList in reverse order.

6)    Iterate ArrayList using foreach loop (Java 8)

If you are using Java 8, you can use forEach loop to iterate through Java ArrayList object in just one line.

Output

How to iterate ArrayList in reverse order?

If you want to iterate ArrayList in reverse order, you can use for loop and start with the end index (i.e. ArrayList’s size – 1 because ArrayList index starts with 0) and go up to the first index (which is 0) as given below.

Output

Alternatively, you can reverse the ArrayList first and then iterate in the normal way to get the elements in the reverse order like given below.

Output

However, reverse method approach is not suggested, because it modifies the original ArrayList. It might even create performance problems if the ArrayList is too large. Plus, if the intention is just to iterate the ArrayList in reverse order, reversing it first is overkill.

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: