Skip to Content

Iterate through elements Java ArrayList using Iterator Example

  1. /*
  2.   Iterate through elements Java ArrayList using Iterator Example
  3.   This Java Example shows how to iterate through the elements of java
  4.   ArrayList object using Iterator.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Iterator;
  9.  
  10. public class IterateThroughArrayListUsingIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create an ArrayList object
  15.     ArrayList arrayList = new ArrayList();
  16.    
  17.     //Add elements to Arraylist
  18.     arrayList.add("1");
  19.     arrayList.add("2");
  20.     arrayList.add("3");
  21.     arrayList.add("4");
  22.     arrayList.add("5");
  23.    
  24.     //get an Iterator object for ArrayList using iterator() method.
  25.     Iterator itr = arrayList.iterator();
  26.    
  27.     //use hasNext() and next() methods of Iterator to iterate through the elements
  28.     System.out.println("Iterating through ArrayList elements...");
  29.     while(itr.hasNext())
  30.       System.out.println(itr.next());
  31.    
  32.   }
  33. }
  34.  
  35. /*
  36. Output would be
  37. Iterating through ArrayList elements...
  38. 1
  39. 2
  40. 3
  41. 4
  42. 5
  43. */