Home » Java Tutorial » Iterator in Java

Iterator in Java




Java

Iterator in Java is an interface that is used to navigate through a collection to retrieve individual elements. A collection may be an ArrayList, LinkedList, HashSet, etc. It is a universal iterator that exists from Java 1.2. Prior to Java 1.2, we use Enumeration as an iterator. Due to several limitations of enumeration, Java introduced the Iterator interface followed by the ListIterator and SplitIterator.

Java iterator

 

First, let us understand about Enumeration and then learn why Iterator was introduced.

Enumeration

Enumeration was the first iterator available since Java 1.0. We can use them to retrieve elements only from Legacy collections like Vector, Hashtable, etc. It supports only read operation and we cannot perform update or delete operation using enumeration.

Methods of Enumeration

Enumeration supports only the below 2 methods:

public boolean hasMoreElements() – It checks if the collection has more elements

public Object nextElement() – Returns the next element in the collection. It throws NoSuchElementException when the collection does not have any elements to traverse.

Example of Enumeration

Below is a simple example of Enumeration to traverse through a Vector collection. We use the elements() method to get access to all the elements in the Vector. Then use the Enumeration object to check if the collection has more elements using the hasMoreElements method. To retrieve the values, use the nextElement method.

import java.util.*;
 public class EnumerationDemo {
   public static void main(String[] args) {
     
     Vector vt = new Vector();
     vt.add("Dev");
     vt.add("Hari");
     vt.add("Rishi");
     
     Enumeration e = vt.elements();
     while(e.hasMoreElements())
       System.out.println(e.nextElement());
   }
 }
Dev
Hari
Rishi

To overcome the limitations of Enumerations, the Iterator interface was available from Java 1.2 onwards.

Iterator in Java

We can use Java iterator to retrieve elements and iterate through any types of Collection. Hence it got its name as a Universal iterator. It supports both read and delete operations. It is unidirectional and supports traversal only in the forward direction. In technical terms, iteration means navigating through each and every element in the collection. Hence it got its name as an Iterator.

READ  Map in Java

Java Iterator methods

Java iterator has 4 supporting methods as discussed below:

MethodDescription
boolean hasNext()Checks if the collection has next element. Returns true if the collection has more elements
String next();Returns the next element. It throws NoSuchElementException if there are no elements
void remove();Removes the next element. It can be used only once per call with next() method.
void forEachRemaining(Consumer action)Performs the specified action for each element until all the elements are processed or the action throws an exception

Working of Iterator in Java

Below are the steps that demonstrate the working of an iterator.

  • Access the iterator method using the Collection object. Iterator<Type> iterator_variable = collectionObject.iterator(); where Iterator is the interface, Type is the data type(String, Integer), iterator_variable is the variable name, collectionObject is the object of any collection like ArrayList, LinkedList.
  • Within the while loop, we check if the collection has the next element using the hasNext method. Initially, the cursor will first point to the position before the first element.
  • If the above condition is true, we can access the element using the next method. It will fetch the next value and then the cursor moves to the first element.
  • This process continues until the hasNext method returns a false value.

Exceptions in Java Iterator

Below are the exceptions thrown by the Java iterator:

  • NoSuchElementException – It throws this exception when there is no element to access using the next method.
  • UnsupportedOperationException – When the iterator does not support the remove method
  • IllegalStateException – When we call the remove method before calling the next method.
  • ConcurrentModificationException – When we add a new value to the collection during iteration.
READ  Polymorphism in Java

Limitations of using Iterator

  • Supports only forward iteration.
  • Cannot update or add any element.

Example of Java iterator

In the below example, we use Java iterator to traverse through an ArrayList. Here age is the ArrayList object.

import java.util.Iterator;
import java.util.ArrayList;

public class IteratorDemo {

  public static void main(String[] args) {
    ArrayList<Integer> age = new ArrayList<Integer>();
    age.add(10);
    age.add(20);
    age.add(30);
    age.add(40);
    age.add(50);
    
    Iterator<Integer> i = age.iterator();
    while(i.hasNext())
      System.out.print(i.next() + " ");

  }

}
10 20 30 40 50

Below is another example of using the iterator in LinkedList to display the elements in the reverse order. This method descendingiterator is available only in the LinkedList collection. Using the iterator method we can print them in the actual order.

import java.util.Iterator;
import java.util.LinkedList;

public class IteratorDemo {

  public static void main(String[] args) {
    LinkedList<String> values = new LinkedList<String>();
    values.add("Kavitha");
    values.add("Sunitha");
    values.add("Pavithra");
    values.add("Lalitha");

    Iterator<String> it = values.descendingIterator();
    System.out.println("Names: ");
    while(it.hasNext())
      System.out.print(it.next() + " ");

    Iterator<String> i = values.iterator();
    System.out.println("\nNames in actual order: ");
    while(i.hasNext())
      System.out.print(i.next() + " ");
  }

}
Names: 
Lalitha Pavithra Sunitha Kavitha 
Names in actual order: 
Kavitha Sunitha Pavithra Lalitha

This is another example of using an iterator to traverse through elements in a Set.

import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;

public class IteratorSetExample {

  public static void main(String[] args) {
    Set<String> setnames = new HashSet<String>();
    setnames.add("Roshan");
    setnames.add("Kiran");
    setnames.add("Tejas");
    setnames.add("Karthik");
    
    Iterator<String> iterator = setnames.iterator();
    while(iterator.hasNext())
      System.out.println(iterator.next());
  }

}
Roshan
Kiran
Tejas
Karthik

Below is an example to remove an element using iterator.

import java.util.*;

public class RemoveIterator {

  public static void main(String[] args) {
    ArrayList<Integer> num = new ArrayList<Integer>();
    for(int i=1;i<=5;i++)
      num.add(i);
    System.out.println("Original numbers:");
    System.out.println(num);
    
    Iterator<Integer> it = num.iterator();
    while(it.hasNext()) {
      int val = (Integer)it.next();
      if(val == 3)
        it.remove();
    }
    System.out.println();
    System.out.println("Numbers after removal:");
    System.out.println(num);	

  }

}
Original numbers:
[1, 2, 3, 4, 5]

Numbers after removal:
[1, 2, 4, 5]

ConcurrentModificationException using Iterator

When we try to add or update the values of the collection while using the iterator, it throws ConcurrentModificationException. Below is an example to illustrate the exception. When we try to add a new String to the LinkedList collection during the iteration, it throws an exception.

import java.util.Iterator;
import java.util.LinkedList;

public class IteratorExample {

  public static void main(String[] args) {
    LinkedList<String> values = new LinkedList<String>();
    values.add("Kavitha");
    values.add("Sunitha");
    values.add("Pavithra");
    values.add("Lalitha");
    
    Iterator<String> i = values.iterator();
    while(i.hasNext()) {
      values.add("Devika");
      System.out.print(i.next() + " ");
    }
      
  }

}
Exception in thread "main" java.util.ConcurrentModificationException
  at java.base/java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:970)
  at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:892)
  at IteratorExample.main(IteratorExample.java:35)

Difference between Enumeration and Iterator

EnumerationIterator
Available from JDK 1.0Available from JDK 1.2
It is not a universal iteratorIt is a universal iterator
It can be used to iterate only legacy collections like Vector, hashtableIt can be used to iterate any Collections
Supports only read operationSupports both read and delete operation
It has lengthy method names
Eg: hasMoreElements()
It has short method names
Eg: hasNext()
READ  Java Super Keyword

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions

AD Blocker Detected !

Advertisements help running this website for free.

To view the content please disable AdBlocker and refresh the page.

Wait !!!

You can Crack Technical Interviews of Companies like Amazon, Google, LinkedIn, Facebook, PayPal, Flipkart, etc

Abhishek

Abhishek was able to crack Microsoft after practicing questions from TutorialCup