5 ways : How to iterate or loop over ArrayList in Java

I have already shared how to sort an ArrayList and how to reverse the ArrayList in java. In this tutorial we will learn how to loop ArrayList in java.

There are 5 ways you can iterate through an ArrayList


1. For Loop

2. Advanced For Loop

3. While loop

4. Iterator

5. Collection's stream() util (using Java 8)

Read Also :      How to find length of an ArrayList in java

Lets write all the ways through which one can iterate or traverse or loop over ArrayList in java.

Program for How to Loop ArrayList in Java :


import java.util.*;
import java.io.*;


public class ArrayListLoopExample
{
 public static void main (String[] args) 
 {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(13);
      al.add(7);
      al.add(36);
      al.add(89);
      al.add(97);


      /*For Loop Example for traversing ArrayList*/
      System.out.println("Using For Loop");
      for (int counter = 0; counter < al.size(); counter++) {   
        System.out.println(al.get(counter));   
      }     

      /* Advanced For Loop Example for iterating ArrayList*/   
      System.out.println("Using Advanced For Loop");   
      for (Integer num : al) {         
        System.out.println(num);   
      }

      /* While Loop Example for iterating ArrayList*/   
      System.out.println("Using While Loop");   
      int count = 0;   
      while (al.size() > count) {
        System.out.println(al.get(count));
        count++;
      }

      /* Iterator Example for Traversing ArrayList */
      System.out.println("Using Iterator");
      Iterator it = al.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }
 
      /* Collection stream() util example */
      System.out.println("Using Collection stream() util");
      al.forEach((num) -> {
      System.out.println(num);
      });
} }

Output
Using For Loop
13
7
36
89
97
Using Advanced For Loop
13
7
36
89
97
Using While Loop
13
7
36
89
97
Using Iterator
13
7
36
89
97
Using Collection stream() util
13
7
36
89
97

Please mention in the comments if you have any questions regarding how to loop ArrayList in java.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry