Skip to content

Java ArrayList for loop for each example

Java ArrayList for loop for each example shows how to iterate ArrayList using for loop and for each loop in Java. It also shows how to use the ArrayList size to loop through the elements of ArrayList.

How to iterate ArrayList using for loop and for each loop in Java?

You can use the size method of ArrayList to get total number of elements in ArrayList and the get method to get the element at the specified index from ArrayList.

Using for loop

Output

ArrayList index starts from 0, so we initialized our index variable i with 0 and looped until it reaches the ArrayList size – 1 index. Inside the loop we print the elements of ArrayList using the get method.

Using enhanced for loop

Iterating over ArrayList using enhanced for loop is a bit different from iterating ArrayList using for loop. When we use the enhanced for loop, we do not need to maintain the index variable as given below.

Output

Using forEach loop (Java 8)?

If you are using Java 8, you can use the forEach to iterate through the List as given below.

Output

You can also visit how to iterate over List example to learn about iterating over List using several ways apart from using for loop and for each loop.

This example is a part of the Java ArrayList tutorial.

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

About the author

Leave a Reply

Your email address will not be published.