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

I have already shared how to sort an ArrayList and how to reverse the ArrayList in java. There are 5 ways you can iterate through the ArrayList.

1. For Loop
2. Advanced For Loop
3. Iterator
4. While loop
5. Collection's stream() util (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.

import java.util.*;
import java.lang.*;
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 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 for Iterating ArrayList*/   
      System.out.println("Using Advanced For Loop");   
      for (Integer num : al) {         
           System.out.println(num);   
      }

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

      /*Traversing ArrayList using Iterator*/
      System.out.println("Using Iterator");
      Iterator it = al.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }
      /* Iterating ArrayList using Collection stream() util */
      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




About The Author

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