In the previous tutorial, we learned types of iterators in java. Now we will learn how to iterate (loop) ArrayList in Java. Basically, there are five ways by which we can iterate over elements of an ArrayList. They are as follows:
1. Using for loop.
2. Using Enhanced for loop or Advanced for loop
3. Using while Loop
4. By using Iterator
5. By ListIterators
How to iterate ArrayList in Java

1. Iterating ArrayList using for loop:


A for loop has the syntax:
   for(initialization; condition; step)
   {
     - - body- - 
     - - - - -- }
Where initialization is a variable declaration. condition is an expression of type boolean, step is an increment/decrement and body is a statement.
The loop is executed as follows:
1. The initialization is executed.
2. The condition is evaluated if it is true, the body is executed. If it is false, the loop terminates.
For example:
 // Get size of the ArrayList.
      int size=al.size();
 // Iterate through all elements.
      System.out.println("for Loop");
      for(int i=0; i<size; i++)
      {
// Call get() method to return or get the elements on the specified index after iterating.
         String getElement=al.get();
         System.out.println(getElement);
      }

2. Iterating ArrayList using Enhanced or Advanced for loop


This Enhanced for loop is introduced in Java 1.5 version. So if you are using Java 1.5 or later, you can use enhanced for statement.
➤ In Enhanced for loop, we don't need to increment or decrement.
➤ No size calculation.
➤ We must use the generic concept to iterate elements of a list.
The syntax for Enhanced for loop:
  for(data_type element : Object reference variable )
    {
       - - - - - -
       - - - - - -
      body
      - - - - - - }

How Enhanced for loop works?


Enhance for loop works in two steps. They are as follows:
1. It iterates over each element in the collection or array.
2. It stores each element in a variable and executes the body.
For example 1:
  ArrayList<String> al=new ArrayList<String>();
   for(String element: al)
    {
       System.out.println(element);
      }
 For example 2:
   ArrayList<Employee> al=new ArrayList<Employee>();
     for(Employee emp: al )
    { 
      System.out.println(emp.name);
      System.out.println(emp.age);
      }
This Enhanced for loop is mostly used in the industry.
Let's see an example program to understand the concept of for loop and enhanced for loop.
Program source code 1:
    package iterateTest; import java.util.ArrayList; public class IterateArrayList { public static void main(String[] args) { // Create object of ArrayList of type String. We can add only String type of element. ArrayList<String> al=new ArrayList<String>(); // Call add() method to add the elements in the list using reference variable al. al.add("A"); al.add("B"); al.add("C"); al.add("D"); al.add("E"); // Displaying original elements of the ArrayList. System.out.println(al); // It will display all elements of ArrayList at a time. // Iterating ArrayList using for loop and call size() method to get the size of elements. Since the return type of size method is an integer. Therefore, we will store it using variable elementsize with type int. System.out.println("Using for loop"); int elementsize=al.size(); System.out.println("Size: " +elementsize); for(int i=0; i < al.size(); i++) { // Call get() method to return the elements on specified index after iterating. String getElement=al.get(i); System.out.println(getElement); } al.set(2, "G"); // It will replace the element at position 2 with element G. al.set(3, null); // adding null element at position 3. // Iterating ArrayList using Enhance for loop. System.out.println("Using Enhance for loop"); for(String element:al){ System.out.println(element); } } }
    Output: [A, B, C, D, E] Using for loop Size: 5 A B C D E Using Enhance for loop A B G null E
Key points: 
Iteration over elements in the ArrayList using Enhanced for loop is fail-fast. That means that we can not add or remove the element in the ArrayList during Iteration otherwise it will throw ConcurrentModificationException.

3. Iterating ArrayList using While loop


Syntax:
   Initialization;
    while(condition) {
         statement1;
         statement2;
         Increment/decrement;
    }


For example:
   System.out.println("Iteration of ArrayList using while loop");
       int i=0; // initialization.
while(ar.size() > i)
 {
    System.out.println(i);
      i++; // Increment.
    }
Let's create an example program where we will iterate elements of ArrayList using while loop concept.
Program source code 2:
    package iterateTest; import java.util.ArrayList; public class IterateUsingWhilelloop { public static void main(String[] args) { ArrayList<Integer> al=new ArrayList<Integer>(); al.add(20); al.add(25); al.add(null); al.add(30); al.add(25); System.out.println(al); // Iteration of ArrayList using while loop. System.out.println("Iteration using while loop"); int i=0; while(al.size()>i){ Integer itr=al.get(i); System.out.println(itr); i++; } } }
    Output: [20, 25, null, 30, 25] Iteration using while loop 20 25 null 30 25

4. Iterating ArrayList using Iterator


iterator() method is used to iterate over elements in the ArrayList in Java. iterator() method is useful when we want to remove the last element during iteration. The Iterator interface defines three methods. They are as follows:
1. hasNext() method: 
This method returns true if the iteration has more elements in the forward direction. 
2. next() method:
It returns the next element in the iteration. If the iteration has no more elements then it will throw "NoSuchElementException".

3. remove() method:
remove() method removes the last element returned by the iterator. This method must be called after calling next() method otherwise, it will throw "IllegalStateException".
Iterators in Java Let's make a program where we will iterate elements of ArrayList by using iterator. We will also remove the last element returned by the iterator.
Program source code 3:
    package iterateTest; import java.util.ArrayList; import java.util.Iterator; public class RemoveTest { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("Apple"); al.add("Mango"); al.add("Banana"); al.add("Guava"); al.add("Pineapple"); System.out.println(al); // It will print all elements at a time. System.out.println("Iteration using iterator concept."); // Create an object of Iterator by calling iterator() method using reference variable al. // At the beginning, itr(cursor) will point to index just before the first element in al. Iterator<String> itr=al.iterator(); // Checking the next element availability using reference variable itr. while(itr.hasNext()){ // Moving cursor to next element using reference variable itr. String str=itr.next(); System.out.println(str); // Removing the pineapple element. if(str.equals("Pineapple")){ itr.remove(); System.out.println("After removing pineapple element"); System.out.println(al); } } } }
    Output: [Apple, Mango, Banana, Guava, Pineapple] Iteration using iterator concept. Apple Mango Banana Guava Pineapple After removing pineapple element [Apple, Mango, Banana, Guava]
Key points:
iterator returned by ArrayList is a fail-fast. That means that if we add an element or remove an element in the ArrayList during the Iteration then it will throw "ConcurrentModificationException" because the loop internally creates a fail-fast iterator which throws an exception whenever any structural modification in the underlying data structure.
Let's make a program where we will understand the concept of fail-fast during iteration of elements.
Program source code 4:
    package iterateTest; import java.util.ArrayList; import java.util.Iterator; public class AddingElementUsingIteration { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("Lion"); al.add("Tiger"); al.add("Elephant"); al.add("Bear"); Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); // Adding element during iteration. Since the return type of add() method is boolean. Therefore, we will store it using variable b with data type boolean. boolean b=al.add("Leopard"); // Compile time error. It will throw ConcurrentModificationException. System.out.println(b); } } }
    Output: Exception in thread "main" java.util.ConcurrentModificationException

5. Iterating ArrayList using ListIterator


In Java programming, ListIterator is used to iterate the elements of ArrayList in both forward as well as backward direction. Using ListIterator, we can start the iteration from a specific element in the ArrayList. We can perform different kinds of operations such as read, remove, replacement (current object), and the addition of the new objects.

Methods of ListIterator


ListIterator interface defines 9 methods in Java. They are as follows:
Since ListIterator is the child interface of Iterator. Therefore, all the methods of Iterator are available by default to ListIterator. ListIterator interface has total of 9 methods. They are as follows:
Forward direction
1. public boolean hasNext()
2. public Object next()
3. public int nextIndex():
It returns the index of the next element in the list. The return type of this method is an integer.

Backward direction
4. public boolean hasPrevious():
It checks that the list has more elements in the backward direction. If the list has more elements, it will return true. The return type is boolean.
5. public Object previous():
It returns the previous element in the list and moves the cursor position backward direction. The return type is Object.
6. public int previousIndex():
It returns the index of the previous element in the list. The return type is an Integer.


Other capability methods
7. public void remove():
Remove the last element returned by next() or previous() from the list. The return type is 'nothing'.
8. public void set(Object o):
It replaces the last element returned by next() or previous() with the new element. 

9. public void add(Object o):
Insert a new element in the list.
Let's make a program where we will iterate elements of ArrayList in both forward and backward direction using ListIterator.
Program source code 5:
    package iterateTest; import java.util.ArrayList; import java.util.ListIterator; public class ArrayListUsingListIterator { public static void main(String[] args) { ArrayList al=new ArrayList(); al.add("First"); al.add("Second"); al.add("Third"); al.add("Fourth"); al.add("Fifth"); System.out.println(al); // Iterating using ListIterator. // Call listIterator() method to create object of ListIterator using reference variable al. ListIterator litr=al.listIterator(); // Here we are not using generic. Therefore, Typecasting is required. // Checking the next element availability in the forward direction using reference variable litr. System.out.println("Iteration in the forward direction"); while(litr.hasNext()){ // Moving cursor to next element in the forward direction using reference variable litr. Object o=litr.next(); String str=(String)o; // Typecasting is required because the return type of next() method is an Object. System.out.println(str); } // Checking the previous element in the backward direction using reference variable litr1. System.out.println("Iteration in the backward direction."); while(litr.hasPrevious()){ // Moving cursor to the previous element in the backward direction. Object o=litr.previous(); String str1=(String)o; // Typecasting. System.out.println(str1); } } }
    Output: [First, Second, Third, Fourth, Fifth] Iteration in the forward direction First Second Third Fourth Fifth Iteration in the backward direction. Fifth Fourth Third Second First
Type Conversion and Casting in Java  Program source code 6: In this example program, we will perform add and remove operations using ListIterator. We will use generic in this program so that we do not require Typecasting.
    package iterateTest; import java.util.ArrayList; import java.util.ListIterator; public class AddRemoveTest { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("One"); al.add("Two"); al.add("Three"); al.add("Nine"); al.add("Five"); al.add("Seven"); System.out.println(al); ListIterator<String> litr=al.listIterator(); while(litr.hasNext()){ String str=litr.next(); if(str.equals("Nine")){ litr.remove(); litr.add("Four"); System.out.println(al); } else if(str.equals("Seven")){ litr.set("Six"); System.out.println(al); } } } }
    Output: [One, Two, Three, Nine, Five, Seven] [One, Two, Three, Four, Five, Seven] [One, Two, Three, Four, Five, Six]
Let's create one more program where we will add elements from 0 to 9 numbers in the list by using "for loop". But we will iterate from a specific element '4' in the list.
Program source code 7:
    package iterateTest; import java.util.ArrayList; import java.util.ListIterator; public class SpecificElementTest { public static void main(String[] args) { ArrayList<Integer> al=new ArrayList<Integer>(); for(int i=0 ; i<=9 ; i++){ al.add(i); } System.out.println(al); ListIterator<Integer> litr=al.listIterator(4); // Iterating through a specific element '4'. while(litr.hasNext()){ Integer it=litr.next(); System.out.println(it); } while(litr.hasPrevious()){ al.add(20); // It will throw ConcurrentModificationException because we can not add element in the ArrayList during Iteration. Integer it1=litr.next(); System.out.println(it1); } } }
    Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 4 5 6 7 8 9 Exception in thread "main" java.util.ConcurrentModificationException
Key points: 
ListIterator returned by ArrayList is also fail-fast. It will throw ConcurrentModificationException. That is we cannot add or remove element in the ArrayList during Iteration.

Final words
Hope that this tutorial has covered almost all important points related to how to iterate ArrayList in Java. This tutorial has covered almost all practical example programs with concepts related to this topic. I hope that you will have understood this topic and enjoyed it.
Thanks for reading!
Next ➤ How to Synchronize ArrayList in Java

⏪ Prev Next ⏩