Iterator In Java With Example

There are different ways by which we can traverse over elements that are for-loop, while loop, do-while, for each loop etc. They all are index based on traversing methods. But as we know Java is purely object oriented  programming language in which we always have possible ways of doing things using objects. So Iterator is a way to traverse the data over the collection objects.

Java Iterator is an Interface that belongs to the collection framework allow us to traverse the collection objects and access the elements of  that collection. Basically List Interface and Set Interface provides the iterator. Iterator can be used with all the implementation of Set and List Interfaces like for example ArrayListLinkedListTreeSet etc.

Map implementation such as HashMap, TreeMap, LinkedHashMap doesn’t provide Iterator directly but we can iterate over them by getting there key-Set or Value Set.


Methods of Iterator

1. boolean hasNext( )

This method returns true if there are more elements else it returns false.

2. Object next( )

This method returns the next element in the collection or else throws NoSuchElementException if there is no next element present.

3. void remove( )

This method removes the current element on which iteretor points to or else throws IllegalStateException if remove( ) method is called that is not preceded by a call to next( ) method.


Types of Iterators

1. fail-fast Iterator

As name suggests fail-fast Iterator fails as soon as the structure of Collection has been changed since traversing has begun. Changes means adding, removing or updating any element from collection while one thread is Iterating over that collection.

fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

2. fail-safe Iterator

Contrary to fail-fast Iterator, fail-safe iterator doesn’t throw any Exception if Collection is modified structurally while one thread is traversing over it as they work on copy of Collection instead of original collection and that is why, they are called as fail-safe iterator.


How to Iterate Over Elements

Every collection class has an iterator() method which returns an iterator object to the beginning of the collection elements. By using this object, we can access each element in the collection and each element at a time.

To use an Iterator to traverse the collection follow these steps:

1. Obtain an Iterator by calling the collection’s iterator( ) method.
2. Create a loop that makes a call to hasNext( ) method.
3. Iterate the loop as long as hasNext() method returns true.
4. In the loop get each element by calling next( ) method.


Example of How to use Iterator with List Interface in Java:

Let us discuss Iterator with List Interface with the help of program, following program has been divided into 3 Steps that we will discuss one by one:

import java.util.*;
public class IteratorExampleDemo{
 

public static void main(String[] args) {

//Step 1: create an ArrayList

List<String> arrayList = new ArrayList<String>();

//Step 2: Add elements in Array List

arrayList.add("I");
arrayList.add("Love");
arrayList.add("JAVA");
 
System.out.println("Iterate Using Iterator");

//Step 3: Iterator object of String type is created
Iterator<String> iterator = arrayList.iterator();

//Step 4: Iterate Using while loop
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

 Output:

Iterate Using Iterator
I
Love
JAVA 

 Description:

  • In Step 1, we have created an object of List Interface that is of String type.
  • In Step 2, we have used add method to add values in the data structure that we have created in step 1.
  • In Step 3, we have created an object of Iterator of type String.
  • In Step 4 we have traversed the data structure with while loop using two methods hasNext() that tell whether there is next element present or not, and next() method that gives the next element during traversing.

Example of How to use Iterator with Set Interface in Java:

Let us discuss Iterator with Set Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one. 

import java.util.*;

public class IteratorExampleDemo{

public static void main(String[] args) {

//Step 1: create an hashSet

Set<String> hashSet = new HashSet<String>();

//Step 2: Add elements in hash Set

hashSet.add("I");
hashSet.add("Love");
hashSet.add("JAVA");

System.out.println("Iterate Using Iterator");

// Step 3: Iterator object of String type is created
Iterator<String> iterator = hashSet.iterator();

//Step 4: Iterate Using while loop
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

Output:

Iterate Using Iterator
JAVA
Love
I

Description:

  • In Step 1, we have created an object of Set Interface that is of String type.
  • In Step 2, we have used add method to add values in the data structure that we have created in step 1.
  • In Step 3, we have created an object of Iterator of type String.
  • In Step 4 we have traversed the data structure with while loop using two methods hasNext() that tell whether there is next element present or not, and next() method that gives the next element during traversing.

Example of How to use Iterator with Map Interface in Java:

Iterating over any of the Map implementations like Hashmap, TreeMap etc is not very straight forward as compared to other collections. Let us discuss Iterator with Map Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class IteratorMapExample {
public static void main(String[] args) {

//Step 1: Object of HahsMap class is Created
Map hashMapObj = new HashMap<String, String>();

//Step 2: values are added using put() method
hashMapObj.put("Abhishek", "A+");
hashMapObj.put("Gaurav", "B+");
hashMapObj.put("Pryanka", "A-");
hashMapObj.put("Rahul", "B+");

System.out.println("Using Iterator");

//Step 3: object of Iterator is Created
Iterator<Map.Entry<String, String>> iterator = hashMapObj.entrySet().iterator() ;

//Step 4: Traveresed Using While loop
while(iterator.hasNext()){
Map.Entry<String, String> bloodGroup = iterator.next();
System.out.println(bloodGroup.getKey() +" :: "+ bloodGroup.getValue());
}
}
}

Output:

Using Iterator

Rahul :: B+
Abhishek :: A+
Gaurav :: B+
Pryanka :: A-

Description:

  • In Step 1, we have created an object of HashMap class, as we know HashMap has key value pair, so we have defined Key of Integer type, and Value of String type.
  • In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.
  • In Step 3, we have created object of Iterator class, that will be used to further traverse the map.
  • In Step 4 weh have used while loop, that has used hasNext() method that tell whether there is next element present or not, and next() method that gives the next element during traversing. And we have used two more methods , First is  getKey() , which as name suggest retrieves the key and secondly getValue() method that retrieves the values corresponding to the keys.

Why use Iterator when we have Enumerator

Both Iterator and Enumerator is used for traversing the collection, then why we need Iterator? Following points will tell why we need Iterator:

  • Iterator is more enhanced as extra method  remove () is provided by which we can modify the collection which is not available in Enumeration .
  • Iterator  is more secure as it doesn’t allow another thread to modify the collection when some another thread is traversing the collection and throwsconcurrentModificationException.
  • Along with above benefits names of methods defined in Iterator are also very convenient which is not major difference but make use of iterator more easy.

Iterator Important Points

  • Iterators are of two types Fail-Fast and Fail-safe, Use Fail-fast when no modifications are needed, else use Fail-safe When modifications such as remove are needed
  • Iterator supports Generics, so always use generic type instead using it as Raw Type
  • Iterator has remove() method which is used instead of using for each loop to avoid ConcurrentModificationException
  • List collection type also supports ListIteratorwhich has add() method to add elements in collection while Iterating that we will discuss in our next topic

Iterator Quick Revision Points

  • Iterator is an Enhancement over Enumeration as it has remove() method
  • Iterator is ThreadSafe as compared to Enumeration
  • Use fail-fast when no modification is needed, use fail-safe when we have to modify data structure while traversing