Iterator in Java | Methods, Iterable Interface, Example

Iterator in Java


An iterator in Java is a special type of object that provides sequential (one by one) access to the elements of a collection object.

In simple words, it is an object that allows us to get and process one element at a time. It is introduced in Java 1.2 Collections Framework.

An Iterator object implements Iterator interface which is present in java.util.Iterator package. Therefore, to use an Iterator, you must import either java.util.Iterator or java.util.*.

Iterator in Java is used in the Collections Framework to retrieve elements sequentially (one by one). It is called universal Iterator or cursors. It can be applied to any collection object. By using Iterator, we can perform both read and remove operations.

Iterable Interface in Java


The Collection interface extends Iterable interface that is present at the top of collection hierarchy. The iterable interface is present in java.lang.Iterable package. It provides a uniform way to retrieve the elements one by one from a collection object.

It provides just one method named iterator() which returns an instance of Iterator and provides access one by one to the elements in the collection object. The general syntax of iterator() method is as follows:

iterator() : Iterator // Return type is Iterator.

How to create Iterator object in Java?


Iterator object can be created by calling iterator() method which is present in the iterable interface. The general syntax for creating Iterator object is as follows:

Iterator itr = c.iterator(); // c is any collection object.
Iterator<Type> itr = c.iterator(); // Generic type.

For example:
 Iterator<String> itr = c.iterator();
 Iterator<Integer> itr = c.iterator();

How Java Iterator works internally?


The basic working mechanism for using Java Iterator is shown in the flow diagram.

Basci working mechanism of Java Iterator

Let’s take an example program to understand how Java Iterator works internally?

Look at the source code of a simple program.

Program source code 1:

import java.util.ArrayList;
import java.util.Iterator;
public class IteratorTest 
{
public static void main(String[] args) 
{
   ArrayList<String> al = new ArrayList<String>();
// Adding elements in the array list. 
   al.add("A");
   al.add("B");
   al.add("C");
   al.add("D");
   al.add("E");
   al.add("F");

Iterator<String> itr = al.iterator();
while (itr.hasNext()) 
{
 String str = itr.next();	
 System.out.print(str + " ");
 }
}
}
Output:
       A B C D E F

When we create an iterator for the collection elements, the iterator looks like the following.

How Java Iterator works internally
1. In the beginning, an Iterator points at right before the first element of the collection as shown in the above figure.

2. When hasNext() method is called on this Iterator, it returns true because elements are present in the forward direction. With the call to the next() method, it returns an element from the collection and sets the Iterator object to the next element on the next call of this method.

3. Again hasNext() method will be called to check that elements are present for iteration. Since elements are present for iteration in the forward direction, therefore, it will return true.

On call of next() method, it will return the next element from the collection and will set the Iterator object to the next element on the next call of this method.

4. Calling of hasNext() and next() method will be continued until the pointer moves to the last element.

5. When the pointer reached the last element of the ArrayList then the call to the hasNext() method will return false and the call to next() method will give an exception named NullPointerException.

Iterator Methods in Java


The Iterator interface provides three methods in Java. They are as follow:

1. public boolean hasNext(): This method will return true if the iteration has more elements to traverse (iterate) in the forward direction. It will give false if all the elements have been iterated.

2. public Object next(): The next() method return next element in the collection. It will throw NoSuchElementException when the iteration is complete.

3. public void remove(): The remove() method removes the last or the most recent element returned by the iterator. It must be called after calling the next() method otherwise it will throw IllegalStateException.

Let’s take some example programs based on these methods in an easy way and step by step. We will use the Iterator concept to traverse all elements in the ArrayList.

Program source code 2:

package iteratorsTest; 
import java.util.ArrayList; 
import java.util.Iterator; 
public class IteratorTest 
{ 
public static void main(String[] args)  
{ 
// Create an object of ArrayList of type Integer. 
  ArrayList<Integer> al = new ArrayList<Integer>(); 
  for(int i = 0; i < = 8; i++)
  {  
   al.add(i); 
  } 
System.out.println(al); // It will print all elements at a time. 

// Create the object of Iterator by calling iterator() method using reference variable al. 
// At the beginning, itr (cursor) will point to index just before the first element in al. 
   Iterator<Integer> itr = al.iterator(); 

// Checking the next element availability using reference variable itr. 
   while(itr.hasNext())
   { 
// Moving cursor to next element using reference variable itr. 
    Integer i = itr.next(); // Here, Type casting does not require due to using of generic with Iterator. 
    System.out.println(i); 

// Removing odd elements. 
   if(i % 2! = 0) 
     itr.remove(); 
   } 
  System.out.println(al); 
 } 
}

Look at the below picture to understand how elements are iterating in the above program.


A conceptual view of iterator in java

Output: 
       [0, 1, 2, 3, 4, 5, 6, 7, 8] 
       0 1 2 3 4 5 6 7 8 
       [0, 2, 4, 6, 8]

Let’s create one more program for practice where we will iterate all the elements in the ArrayList using iterator() method.

Program source code 3:

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

public class IteratorTest {
public static void main(String[] args) 
{
Collection<String> collection = new ArrayList<>();

// Adding elements in the array list. 
   collection.add("Red");
   collection.add("Green");
   collection.add("Black");
   collection.add("White");
   collection.add("Pink");

 Iterator<String> iterator = collection.iterator();

 while (iterator.hasNext()) 
 {
   System.out.print(iterator.next().toUpperCase() + " ");
 }
System.out.println();
 }
}
Output:
       RED GREEN BLACK WHITE PINK

Difference between Enumeration and Iterator


Both are useful to retrieve elements from a collection. But the main difference between Enumeration and iterator is with respect to functionality.

By using an enumeration, we can perform only read access but using an iterator, we can perform both read and remove operation.

Advantage of Iterator in Java


Java Iterator has the following advantages. They are as follows:

  • An iterator can be used with any collection classes.
  • We can perform both read and remove operations.
  • It acts as a universal cursor for collection API.

Limitation of Iterator in Java


Iterator has the following limitations or drawbacks. They are as:

1. By using Enumeration and Iterator, we can move only towards forwarding direction. We cannot move to the backward direction. Hence, these are called single direction cursors.
2. We can perform either read operation or remove operation.
3. We cannot perform the replacement of new objects.

For example, suppose there are five mangoes in a box. Out of five, two mangoes are not good but we cannot replace that damaged mangos with new mangos.

To overcome the above drawbacks, we should use the ListIterator concept.

Hope that this tutorial has covered all important points related to iterator in Java with example program. I hope that you will have understood the basic point of iterable interface in Java.

In the next tutorial, we will learn ListIterator in Java.

Thanks for reading!!!