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.


2)    Iterate ArrayList using for loop

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


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.


4)    Iterate ArrayList using Iterator

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


5)    Iterate ArrayList using ListIterator

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


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.


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.


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.


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.

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

1 Comment

Your email address will not be published. Required fields are marked *