Collections

Java ArrayList for loop for each example

Java ArrayList for loop for each example shows how to iterate ArrayList using for loop, for each loop in Java. It also shows how to loop through ArrayList using for loop, for each loop using size and get methods.

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

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

How to loop 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. Inside the loop we printed elements of ArrayList using get method.

How to loop ArrayList using enhanced for loop?

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

Output

How to loop ArrayList using forEach loop (Java 8)?

If you are using Java 8, you can use 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.

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.