Java Iterator In Details

Java iterator interface is used to iterate (loop) different elements of collection classes like HashMap, ArrayList, LinkedList, etc. In our previous post regarding the Java Collection framework tutorial, we learned about different classes and interfaces like ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, HashMap, TreeMap, LinkedHashMap & Hashtable. But in this article, we will learn how to get the elements one by one using different cursors of Java.

Different Types of Cursors

Before starting the different types of cursors, we have to know what a cursor is. A cursor is nothing but an iterator that we use to iterate, traverse, or retrieve the collection elements individually.

Java programming language supports four different types of cursors:

  • Enumeration
  • Iterator
  • ListIterator
  • Spliterator

The above iterator has some advantages and also some drawbacks. Let’s try to find the disadvantages and advantages in detail.

Enumeration

This interface is used to get the elements of the legacy collections classes (Vector, Hashtable). This iterator is introduced in the Java 100 version. The enumeration class is used to specify the input stream to a SequenceInputStream, and we can create an Enumeration object by calling elements() of the vector class.

This Enumeration class has mainly two classes:

  • Public boolean hasMoreElements(); For Test, does the enumeration class have more elements?
  • public Object nextElement(); It returns the next elements of the enumeration, and if there are no more elements, then it will throw NoSuchElementException
// Java program to demonstrate Enumeration
import java.util.Enumeration;
import java.util.Vector;

public class Test
{
   public static void main(String[] args)
   {
      // Create a vector and print its contents
      Vector v = new Vector();
      for (int i = 0; i < 10; i++)
         v.addElement(i);
      System.out.println(v);

      // At beginning e(cursor) will point to
      // index just before the first element in v
      Enumeration e = v.elements();

      // Checking the next element availability
      while (e.hasMoreElements())
      {
         // moving cursor to next element
         int i = (Integer)e.nextElement();

         System.out.print(i + ” “);
      }
   }
}

Drawbacks Of Enumeration

  • It is useful for only legacy classes like Vector and Hashtable.
  • Compared to the other iterators, method enumeration methods and names are lengthy, like hasMoreElements and nextElement.
  • It supports only forward direction; that’s why it’s also called a uni-directional cursor.
  • As it supports legacy classes only, it’s not recommended for use in new projects.
  • It does not support CRUD operation. Enumeration only Supports the READ operation and does not support other operations like WRITE, UPDATE, AND DELETE.

Note: What is CRUD In Collection API?

  • CREATE: Adding new elements to the collection object.
  • READ Retrieving elements from the collection object.
  • UPDATE: Updating the existing element of the collection object.
  • DELETE: Removing the elements from the collection object.

Because of the above drawbacks in enumeration, Java comes up with another cursor in Java 1.2: the Iterator and listIterator.

Java Iterator

Java iterator interface is present in the Java collection framework in the Java.util package. You can use this iterator, which has implemented interfaces like Set, List, Queue, Deque, and all implemented Map interface classes.

We can create the object of an iterator with the help of the iterator() of the collection interface.

Iterator itr = c.iterator();
  • This iterator is used to retrieve collection objects one by one.
  • This iterator is introduced in the Java 1.2 version.
  • It applies to all collection objects. That’s why it is also called a Universal iterator.
  • It Supports Both READ and REMOVE operations.
  • Compared to the enumeration method name, iterator method names are simple.

Java Iterator Methods

It has three methods to operate with the elements of an iterator, that’s are:

  • hasNext() – Returns true if the iteration has the next elements
  • next() – It returns the next elements of the iteration and throws NoSuchElementException when there are no more elements
  • Remove () – This method helps remove elements from the iteration. This method can be called once per call to the next() method. when you are using this method, you may get two different types of exceptions, which are

UnsupportedOperationException: If the iterator does not support the remove operation, you will get such an exception.
IllegalStateException: If the next method is not called or the remove method is called once after that, you will get this error if you try to execute the remove() method that time.

// Java program to demonstrate Iterator
import java.util.ArrayList;
import java.util.Iterator;
public class Test
{
   public static void main(String[] args)
   {
      ArrayList al = new ArrayList();
      for (int i = 0; i < 10; i++)
         al.add(i);

      System.out.println(al);

      // at beginning itr(cursor) will point to
      // index just before the first element in al
      Iterator itr = al.iterator();

      // checking the next element availabilty
      while (itr.hasNext())
      {
         // moving cursor to next element
         int i = (Integer)itr.next();

         // getting even elements one by one
         System.out.print(i + ” “);

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

Advantages of Iterator

As compared to the enumeration, java iterators have the following advantages:

  • We can use it in any collection class.
  • It Supports both READ and REMOVE operations.
  • It’s a Universal cursor.
  • Method names are simple and easy to use.

Disadvantages of Iterator

Still, there are some disadvantages of Iterator, like below:

  • It does not support the CRUD operation fully, just like the Update and Create operation, which is not supported.
  • You can access a collection class’s forward elements, so this is a unidirectional cursor.

To overcome such a problem, Java programming language has introduced one more cursor type in the Java 1.2 version: ListIterator.

ListIterator

Like Iterator, this also retrieves elements from the collection class, but it’s for list implemented objects.

We can create a list iterator object by following the below syntax:

// Where l is any List Object
ListIterator ltr = l.listIterator();
  • It extends the Iterator interface.
  • It is implemented for the List to implement the interface.
  • It supports all four types of CRUD operation, like CREATE, READ, UPDATE, AND DELETE
  • It supports forward and Backward direction iterations; that’s why this is called bidirectional iterator.
  • ListIterator does not have a current location, and its cursor always lies in between the element that would be returned by a call to the previous() and the element that would be replaced by a call to the next()

Java ListIterator Methods

  • public boolean hasNext(); this method returns true if the iteration has more elements.
  • Public Object next(); Returns the next element of the iterator
  • public int nextIndex(); Returns the next element index. If the cursor is at the last position, it will return the list size.
  • Public boolean hasPrevious(); Returns true if the iteration has more elements when traversing in the backward direction.
  • Public Object previous(); These methods return the previous elements, and if there are no more elements, then it will throw a NoSuchElementException
  • public int previousIndex(); It will return the last index element and -1 if the cursor is at the beginning of the list
  • public void remove(); It will remove the elements from the collection
  • Public void set(Object obj); this method helps when you want to replace the element that is provided by the next() or previous() method with a specified element.
  • public void add(Object obj); By using this, you can insert your element into the collection before the position which is returned by the next() method

When you try to use Set() & add() method, you may get below exceptions:

  • UnsupportedOperationException: If the list iterator does not support the set operation.
  • ClassCastException: If the class of the specified element is not allowed to be added to the list
  • IllegalArgumentException: Due to some reason, some specified element prevents it from being added to the list.
  • IllegalStateException: If neither next nor previous have been called, or remove or add have been called after the last call to next or previous
// Java program to demonstrate ListIterator
import java.util.ArrayList;
import java.util.ListIterator;

public class Test
{
   public static void main(String[] args)
   {
      ArrayList al = new ArrayList();
      for (int i = 0; i < 10; i++)
         al.add(i);

      System.out.println(al);

      // at beginning ltr(cursor) will point to
      // index just before the first element in al
      ListIterator ltr = al.listIterator();

      // checking the next element availabilty
      while (ltr.hasNext())
      {
         // moving cursor to next element
         int i = (Integer)ltr.next();

         // getting even elements one by one
         System.out.print(i + ” “);

         // Changing even numbers to odd and
         // adding modified number again in
         // iterator
         if (i%2==0)
         {
            i++; // Change to odd
            ltr.set(i); // set method to change value
            ltr.add(i); // to add
         }
      }
      System.out.println();
      System.out.println(al);
   }
}

Advantages of listIterator

  • It supports CRUD operations fully, like CREATE, READ, UPDATE, AND DELETE
  • You can traverse forward and backward directions, also called a bidirectional cursor.

Disadvantages of ListIterator

  • You can use this iterator only with the List implemented classes, but like an iterator, you can not use it with all collection API.

Write a program for retrieving elements in the collection using an iterator.

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MyCollectionIterator {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      List<String> myList = new ArrayList<String>();
      myList.add("Java");
      myList.add("Unix");
      myList.add("Oracle");
      myList.add("C++");
      myList.add("Perl");
      Iterator<String> itr = myList.iterator();
      while(itr.hasNext())
      {
         System.out.println(itr.next());
      }
   }
}

Output:

Java
Unix
Oracle
C++
Perl

ListIterator Example

Write a Program to Retrieve an Element from the List Iterator With Example.

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class MyListIterator {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      List<Integer> li = new ArrayList<Integer>(); 
      ListIterator<Integer> litr = null; 
      li.add(23); 
      li.add(98); 
      li.add(29); 
      li.add(71); 
      li.add(5); 
      litr=li.listIterator(); 
      System.out.println("Elements in forward directiton"); 
      while(litr.hasNext())
      {
         System.out.println(litr.next()); 
      }
      System.out.println("Elements in backward directiton"); 
      while(litr.hasPrevious())
      {
         System.out.println(litr.previous()); 
      }
   }
}

Output:

Elements in forward directiton
23
98
29
71
5
Elements in backward directiton
5
71
29
98
23

Iterator Example: How to Print Iterate LinkedHashSet Elements In Java With Example?

package com.java.Softwaretestingblog;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class LinkedHashSetIteratorExample {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      LinkedHashSet<String> lhs = new LinkedHashSet<String>();
      //add elements to HashSet
      lhs.add("first");
      lhs.add("second");
      lhs.add("third");
      Iterator itr = lhs.iterator();
      while(itr.hasNext()){
         System.out.println(itr.next());
      }
   }
}

Output:

first
second
third

Java Iterator Uses In Java Program: How to Add & Retrieve From HashSet Using Java Iterator?

package com.java.Softwaretestingblog;
import java.util.HashSet;
import java.util.Iterator;
public class IteratorExample {
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      //add elements to HashSet
      hs.add("first");
      hs.add("second");
      hs.add("third");
      Iterator<String> itr = hs.iterator();
      while(itr.hasNext())
      {
         System.out.println(itr.next());
      }
   }
}

Output:

third
first
second

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment