Iterate through a Collection using an Iterator in Java

Java 8Object Oriented ProgrammingProgramming

A collection in Java provides an architecture to handle a group of objects. The different classes in the Java Collection Framework are ArrayList, LinkedList, HashSet, Vector etc.

An Iterator can be used to iterate through a Collection and a program that demonstrates this using ArrayList is given as follows −

Example

 Live Demo

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

Output

The ArrayList elements are:
John
Peter
Harry
James
Arthur

Now let us understand the above program.

The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows −

ArrayList<String> aList = new ArrayList<String>();
aList.add("John");
aList.add("Peter");
aList.add("Harry");
aList.add("James");
aList.add("Arthur");
System.out.println("The ArrayList elements are: ");
for (Iterator i = aList.iterator(); i.hasNext();) {
   System.out.println(i.next());
}
raja
Published on 30-Jan-2019 06:47:43
Advertisements