Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of Iterator.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate the use of Iterator.

Objective

Write a Java program to iterate over a Collection using an Iterator.

Algorithm / Approach

  1. Create an ArrayList and populate it with Strings.
  2. Obtain an iterator from the list: Iterator i = al.iterator();.
  3. Use a while loop with the condition i.hasNext().
  4. Inside the loop, retrieve the current element using i.next() and print it.
Test.java
import java.util.*;
class Test {
 public static void main(String[] a)
 {
  ArrayList al = new ArrayList();
  al.add("Alok");
  al.add("Jeet");
  al.add("Anup");
  al.add("Ayan");
  al.add("Arif");
  Iterator i = al.iterator();
  while(i.hasNext()) {
   System.out.print(i.next()+"    ");
  }
 }
}

Expected Output

Alok    Jeet    Anup    Ayan    Arif

Explanation of the Program

  • The Iterator interface provides a standardized way to traverse through any Collection in Java, completely hiding the underlying data structure (whether it's an array, a linked list, or a tree).
  • hasNext() checks if there are more elements left in the collection.
  • next() actually retrieves the current element and advances the internal cursor to the next element.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT