Iterator Interface In Java - GeeksforGeeks

09 Nov, 2020
Java Iterator Interface of java collections allows us to access elements of the collection and is used to iterate over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a collection and perform operations on each element. Iterator is a universal iterator as it can be applied to any Collection object. We can traverse only in the forward direction using iterator. Using ListIterator which extends Iterator, can traverse in both directions. Both read and remove operations can be performed by the iterator interface. This is included in Java JDK 1.2. The only Enumeration is the first iterator to be included in JDK 1.0. To use an iterator, we must import java.util package.
Limitations of Enumeration Interface:
An Iterator interface is used in place of Enumeration in Java Collection. 
Enumeration is not a universal iterator and is used for legacy classes like Vector, Hashtable only.
Iterator allows the caller to remove elements from the given collection during iterating over the elements.
Only forward direction iteration is possible in an Enumeration.
Declaration of iterator interface
public interface Iterator<E>

E – the type of elements returned by this iterator
EventIterator: 
public interface EventIterator extends Iterator<Event>

EventIterators are unmodifiable.
Methods: nextEvent() which returns the next Event in an EventSet.
ListIterator<E>:
public interface ListIterator<E> extends Iterator<E>

An Iterator for lists which allows to traverse the list in either of the forward or backward direction or modify the list during the iteration and to obtain the current position of the iterator. ListIterator has no current element.
PrimitiveIterator<T,T_CONS>, PrimitiveIterator.OfInt, PrimitiveIterator.OfLong
Implementing Classes:
BeanContextSupport.BCSIterator
EventReaderDelegate
Scanner
Example: Implementation of Iterator
All classes in the Collection Framework provide iterator() method which returns the instance of Iterator to iterate over the elements in that collection.
Java
// Java program to show the usage of Iterator()import java.util.Iterator;import java.util.LinkedList;import java.util.List;public class JavaIteratorExample1 {    public static void main(String[] args)    {          // create a list        List<String> list = new LinkedList<>();        list.add("Welcome");        list.add("to");        list.add("GFG");          System.out.println("The list is given as : "                           + list);                      // get the iterator on the list        Iterator<String> itr = list.iterator();          // Returns true if there are more number of        // elements.        while (itr.hasNext()) {            // Returns the next element.            System.out.println(itr.next());        }          // Removes the last element.        itr.remove();        System.out.println(            "After the remove() method is called : "            + list);    }}
The list is given as : [Welcome, to, GFG]
Welcome
to
GFG
After the remove() method is called : [Welcome, to]
ArrayList Iterator Example
Java
// Java program to iterate over an arraylist// using Iteratorimport java.util.*;class GFG {    public static void main(String[] args)    {        // initializing ArrayList        List<Integer> numbers            = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80);          // Looping ArrayList using Iterator        Iterator it = numbers.iterator();        while (it.hasNext())            System.out.print(it.next() + " ");    }}
10 20 30 40 50 60 70 80 
Develop Custom Class Iterator
To provide similar functionality for user-defined /custom class, we should follow the below steps:
Define a custom class.
Define the collection class to this custom class.
The collection class should import java.util package and implement iterable interface.
This collection class should now provide implementation to Iterable interface’s method iterator().
Example code of developing custom class:
Java
// java program to show the creation of// custom class that implements iterable interfaceimport java.util.*;import java.io.*;class Employees implements Iterable {      List<String> str = null;    public Employees()    {        str = new ArrayList<String>();        str.add("practice");        str.add("geeks");        str.add("for");        str.add("geeks");        str.add("to");        str.add("learn");        str.add("coding");    }      // if we are implementing Iterable interface, the we    // need to define the iterator() method of Iterable    // interface    @Override public Iterator<String> iterator()    {        return str.iterator();    }}  public class EmployeesTester {    public static void main(String[] args)    {        Employees emps = new Employees();        for (String st : emps.str) {            System.out.println(st);        }    }}
practice
geeks
for
geeks
to
learn
coding
Using remove() method to remove items from a collection
It removes the last element of the collection returned by the iterator.
If the iteration is in progress and meanwhile underlying collection is modified then by calling remove() method, an Iterator will throw a ConcurrentModificationException.
Java
// java program to remove()// elements from a collection  import java.util.ArrayList;import java.util.Iterator;  public class MyClass {    public static void main(String[] args)    {          // create a list of Integers        ArrayList<Integer> numbers            = new ArrayList<Integer>();        numbers.add(12);        numbers.add(8);        numbers.add(2);        numbers.add(23);                      // get the iterator on the list        Iterator<Integer> it = numbers.iterator();        while (it.hasNext()) {                              // gives the next element              // and iterator moves to next               // element            Integer i = it.next();              if (i < 10) {                                      // removes the current element                it.remove();             }        }        System.out.println(numbers);    }}
[12, 23]
Iterator forEachRemaining() Example
Java
// Java program to show the usage of// Iterator forEachRemaining()import java.util.*;class GFG {    public static void main(String[] args)    {        //  initializing ArrayList        List<Integer> numbers            = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80);          numbers.iterator().forEachRemaining(            System.out::println);    }}
10
20
30
40
50
60
70
80

Advantages of Java Iterator:
It is not a legacy interface and can traverse overall collections like ArrayList, HashMap, TreeSet, HashSet etc.It can be used for any java collection and therefore known as Universal Cursor for Collection API.Read and Remove operations are supported.Simple and easily usable method names.
It is not a legacy interface and can traverse overall collections like ArrayList, HashMap, TreeSet, HashSet etc.
It can be used for any java collection and therefore known as Universal Cursor for Collection API.
Read and Remove operations are supported.
Simple and easily usable method names.
Limitations of Java Iterator:
It does not support Create and Update operations in CRUD (Create, Read, Update, Delete) operations.It supports only uni-directional traversal i.e in forwarding direction.It does not support a better iteration on a large volume of data in comparison to Spliterator.It supports only sequential iteration i.e it does not support iterating elements parallel.
It does not support Create and Update operations in CRUD (Create, Read, Update, Delete) operations.
It supports only uni-directional traversal i.e in forwarding direction.
It does not support a better iteration on a large volume of data in comparison to Spliterator.
It supports only sequential iteration i.e it does not support iterating elements parallel.
Difference between Iterator and Enumeration:
Iterator
Enumeration
Methods:
                 Methods                               
If iteration has more elements, then it returns true.
If the iterator has gone through all the elements, it returns false
It returns the next element of iteration.
It throws NoSuchElementException if the iterator has no more elements.
It removes the last element of the collection returned by the iterator.
If the iteration is in progress and meanwhile underlying collection is modified then by calling remove() method, iterator will throw an ConcurrentModificationException.
It performs the given action for each remaining element until all elements have been processed.
If the order is specified, the actions are performed in the order of iteration.
It throws NullPointerException if the action is null.
Java-Iterator
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java