Iterate through ArrayList in Java


The iterator can be used to iterate through the ArrayList wherein the iterator is the implementation of the Iterator interface. Some of the important methods declared by the Iterator interface are hasNext() and next().

The hasNext() method returns true if there are more elements in the ArrayList and otherwise returns false. The next() method returns the next element in the ArrayList.

A program that demonstrates iteration through ArrayList using the Iterator interface is given as follows

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String> aList = new ArrayList<String>();
      aList.add("Adam");
      aList.add("John");
      aList.add("Nancy");
      aList.add("Peter");
      aList.add("Mary");
      Iterator i = aList.iterator();
      System.out.println("The ArrayList elements are:");
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

The output of the above program is as follows

The ArrayList elements are:
Adam
John
Nancy
Peter
Mary

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. Then the ArrayList elements are displayed using the Iterator interface. A code snippet which demonstrates this is as follows

List<String> aList = new ArrayList<String>();
aList.add("Adam");
aList.add("John");
aList.add("Nancy");
aList.add("Peter");
aList.add("Mary");
Iterator i = aList.iterator();
System.out.println("The ArrayList elements are:");
while (i.hasNext()) {
   System.out.println(i.next());
}

Updated on: 29-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements