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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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