Iterator in Java with Example

The Java iterator comes under the concept of Java Cursors. As the name suggests, it iterates a collection or stream of objects one by one. This segment of the article lets you dive deep into java iterators. Let’s start!!!

What is an Iterator in java?

In Java’s Collection framework, iterators play a vital role in retrieving the elements one by one. It is termed a universal iterator as we can apply it to any Collection of objects. We can easily perform read and write operations using these iterators.

It is basically an upgraded version of enumeration with the additional functionality of removing an element. It belongs to java.util package and is available for free since Java1.2 Collection framework. Comparing the Java Iterator interface and enumerator interface, the method names in the former are accurate and easy to use.

How to use Java Iterator?

To use an iterator, we need an instance of the Iterator interface from the collection of objects that wish to traverse. Later, this iterator acts as the trail of components to ensure that they traverse over every element. In the event of any modification by the user during traversing, the iterator throws an exception.

Syntax to create the iterator object:

Iterator i = c.iterator();

Here, c is the collection of objects, and i is the type of iterator interface.

Java Iterator Methods:

The four methods that you can find in Jaa Iterator interface is:

1. boolean hasNext(): This method returns true if there are elements present for iteration. When there are no more elements left, it returns false. In such a case, it does not call the next() method. No parameters are allowed with this method.

2. E next(): This method is similar to hasNext() and does not admit parameters. All it returns is E, which is the next element in the traversal. When there are no more elements left for traversal, it throws the NoSuchElementException.

3. default void remove(): Same as the above methods, even this method requires no parameters. It also returns nothing. The purpose of this method is to remove the last element that the iterator returns. The remove() method is requested at least once per the next() method. It also throws UnsupportedOperationException when the iterator does not support the remove operation. If the next method is not called, it throws the IllegalStateException error.

4. default void forEachRemaining(Consumer action): This is a parameterized method. It has no return type.

Similarities between Java Enumeration and Iterator:

  • Both are Java cursors.
  • They iterate a collection of object elements one by one.
  • Both support READ or Retrieval operation.
  • They are Uni-directional Java cursors and support only Forward Direction Iteration.

Differences between Java Enumeration and Iterator:

Enumeration Iterator
Introduced in Java 1.0 Introduced in Java 1.2
Legacy Interface Not Legacy Interface
It iterates only Legacy Collection classes It can be used for any Collection class
This supports only READ operation It supports READ and DELETE operations
It is not a Universal Cursor This is a Universal Cursor
It contains lengthy method names It is simple and easy-to-use method names

Advantages of Java Iterator:

  • Java Iterator lets us use the read and remove operations.
  • We can apply the iterators to any class of the Collection framework.
  • Java Iterators are the Universal Cursor for the Collection API
  • The method names in Java Iterator are easy and simple to use.
  • When a user works with a for loop, they cannot add or remove the collection. If they use Java Iterator, they can update the Collection.

Disadvantages of Java Iterator:

  • Though there are various advantages of using Java Iterator, it also has some disadvantages.
  • The Java Iterator carries iteration in the forward direction, and hence it is a uni-directional iterator.
  • Java Iterator does not approve the replacement and extension of new components.
  • It does not contain operations like create and update.
  • When compared with Spliterator, the Java iterator does not let parallel traversing take place. It supports only Sequential iteration.
  • It also does not support reliable execution to traverse a large volume of data.

Example for Java Iterator:

import java.io.*;
import java.util.*;
public class FirstCode{
public static void main(String args[]){
ArrayList<String> courseNames = new ArrayList <String>();
courseNames.add(“Java”);
courseNames.add(“C”);
courseNames.add(“C++”);
courseNames.add(“Python”);
Iterator i = courseNames.i();
System.out.println(“The Courses are:”); 
while(i.hasNext())
System.out.print(i.next() + “ ”);
System.out.println();
}
} 

Output:

The courses are:
Java C C++ Python

Conclusion:

This article has elucidated about iterators in Java. Iterators help us to traverse through the elements of the Collection object. I hope you would have understood it clearly.

Leave a Reply

Your email address will not be published. Required fields are marked *