Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to use Iterator Interface to iterate/traverse Java Collections ?.

Program to demonstrate Iterator Interface to traverse a Java Collection

package com.hubberspot.collections.example;

import java.util.*;

public class IteratorExample
{
 public static void main(String[] args)
 {
  ArrayList list = new ArrayList();
  list.add("One");
  list.add("Two");
  list.add("Three");
  list.add("Four");
  
  Iterator iterate = list.iterator();
  while(iterate.hasNext())
  {
      String element = (String)iterate.next();
      System.out.println("Element = " + element);
         
      iterate.remove();  
 } 
 
   System.out.println("Array list contains"
      + list);
}
}


Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot