Skip to content

Java ArrayList Iterate Example

Java ArrayList iterate example shows various ways to iterate through ArrayList. The 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) Using while loop

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

Output

2) Using for loop

You can use the for loop as well.

Output

3) Using enhanced for loop (Java 1.5 and above version)

If you are using Java version 1.5 and above, you can use enhanced for loop.

Output

4) Using Iterator

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

Output

5) Using ListIterator

The ListIterator can also be used instead of an Iterator. Get the ListIterator object of an ArrayList using listIterator() method.

Output

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

6) 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.

This example is a part of the ArrayList in Java tutorial.

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

About the author

1 comments

Leave a Reply

Your email address will not be published.