Iterator

Iterators in Java are used in the Collection framework to retrieve elements one by one. It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of removing an element.

Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque, and all implemented classes of Map interface. The iterator is the only cursor available for the entire collection framework. An iterator object can be created by calling the iterator() method present in the Collection interface.

Syntax

Iterator itr = c.iterator();

Note: Here “c” is any Collection object. itr is of type Iterator interface and refers to “c”.

Methods of Iterator Interface in Java

The iterator interface defines three methods as listed below:

1. hasNext(): Returns true if the iteration has more elements.

public boolean hasNext();

2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more element is present.

public Object next();

3. remove(): Removes the next element in the iteration. This method can be called only once per call to next().

public void remove();

Note: remove() method can throw two exceptions namely as follows:

  • UnsupportedOperationException : If the remove operation is not supported by this iterator
  • IllegalStateException : If the next method has not yet been called, or the remove method has already been called after the last call to the next method.

How Does Java Iterator Work Internally?

 In this section, we will try to understand how Java Iterator and its methods work internally. Let us take the following LinkedList object to understand this functionality.

List<String> cities = new LinkedList<>(); 
cities.add("G-1");
cities.add("G-2");
cities.add("G-3");
.
.
.
cities.add("G-n");

Now, let us create an Iterator object on the List object as shown below:

Iterator<String> citiesIterator = cities.iterator();

The “citiesIteartor” iterator will look like this –

 

Here Iterator’s Cursor is pointing before the first element of the List.

Now, we will run the following code snippet.

citiesIterator.hasNext();
citiesIterator.next();

 

When we run the above code snippet, Iterator’s Cursor points to the first element in the list as shown in the above diagram.

Now, we will run the following code snippet.

citiesIterator.hasNext();
citiesIterator.next();

 

When we run the above code snippet, Iterator’s Cursor points to the second element in the list as shown in the above diagram. Do this process to reach the Iterator’s Cursor to the end element of the List.

 

After reading the final element, if we run the below code snippet, it returns a “false” value.

citiesIterator.hasNext();

As Iterator’s Cursor points to the after the final element of the List, hasNext() method returns a false value.

Note: After observing all these diagrams, we can say that Java Iterator supports only Forward Direction Iteration as shown in the below diagram. So it is also known as Uni-Directional Cursor.

Example

Java
// Java program to Demonstrate Iterator

// Importing ArrayList and Iterator classes
// from java.util package
import java.util.ArrayList;
import java.util.Iterator;

// Main class
public class Test {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an ArrayList class object
        // Declaring object of integer type
        ArrayList<Integer> al = new ArrayList<Integer>();

        // Iterating over the List
        for (int i = 0; i < 10; i++)
            al.add(i);

        // Printing the elements in the List
        System.out.println(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  where
        // condition holds true till there is single element
        // in the List using hasnext() method
        while (itr.hasNext()) {
            //  Moving cursor to next element
            int i = itr.next();

            // Getting elements one by one
            System.out.print(i + " ");

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

        // Command for next line
        System.out.println();

        // Printing the elements inside the object
        System.out.println(al);
    }
}

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


SplitIterator

Spliterators, like other Iterators, are for traversing the elements of a source. A source can be a Collection, an IO channel, or a generator function. It is included in JDK 8 for support of efficient parallel traversal(parallel programming) in addition to sequential traversal. Java Spliterator interface is an internal iterator that breaks the stream into smaller parts. These smaller parts can be processed in parallel. 

Note: In real life programming, we may never need to use Spliterator directly. Under normal operations, it will behave exactly the same as Java Iterator.

Advantages of Java Iterator

  • We can use it for any Collection class.
  • It supports both READ and REMOVE operations.
  • It is a Universal Cursor for Collection API.
  • Method names are simple and easy to use them.

Limitations of Java Iterator

Also, there are certain limitations of Iterator which are listed as follows:

  • In CRUD Operations, it does NOT support CREATE and UPDATE operations.
  • It supports only Forward direction iteration that is a Uni-Directional Iterator.
  • Compare to Spliterator, it does NOT support iterating elements parallel which means it supports only Sequential iteration.
  • Compare to Spliterator, it does NOT support better performance to iterate large volumes of data.

Iterators in Java

A Java Cursor is an Iterator, that is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one. In this article, we will learn about Java Iterators and it’s working.

 

Similar Reads

Types of Cursors in Java

There are three cursors in Java as mentioned below:...

1. Iterator

Iterators in Java are used in the Collection framework to retrieve elements one by one. It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of removing an element....

2. Enumeration

It is an interface used to get elements of legacy collections(Vector, Hashtable). Enumeration is the first iterator present from JDK 1.0, rests are included in JDK 1.2 with more functionality. Enumerations are also used to specify the input streams to a SequenceInputStream. We can create an Enumeration object by calling elements() method of the vector class on any vector object...

3. ListIterator

It is only applicable for List collection implemented classes like ArrayList, LinkedList, etc. It provides bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator. ListIterator object can be created by calling listIterator() method present in the List interface....

Contact Us