Iterator Interface In Java
Last Updated :
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
Subinterfaces of 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
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class JavaIteratorExample1 {
public static void main(String[] args)
{
List<String> list = new LinkedList<>();
list.add( "Welcome" );
list.add( "to" );
list.add( "GFG" );
System.out.println( "The list is given as : "
+ list);
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
itr.remove();
System.out.println(
"After the remove() method is called : "
+ list);
}
}
|
Output
The list is given as : [Welcome, to, GFG]
Welcome
to
GFG
After the remove() method is called : [Welcome, to]
ArrayList Iterator Example
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList( 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 );
Iterator it = numbers.iterator();
while (it.hasNext())
System.out.print(it.next() + " " );
}
}
|
Output
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
import 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" );
}
@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);
}
}
}
|
Output
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
import java.util.ArrayList;
import java.util.Iterator;
public class MyClass {
public static void main(String[] args)
{
ArrayList<Integer> numbers
= new ArrayList<Integer>();
numbers.add( 12 );
numbers.add( 8 );
numbers.add( 2 );
numbers.add( 23 );
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
Integer i = it.next();
if (i < 10 ) {
it.remove();
}
}
System.out.println(numbers);
}
}
|
Iterator forEachRemaining() Example
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList( 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 );
numbers.iterator().forEachRemaining(
System.out::println);
}
}
|
Output
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.
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.
Difference between Iterator and Enumeration:
Iterator
|
Enumeration
|
It was introduced in JDK 1.2. |
It was introduced in JDK 1.0. |
It is a universal Cursor.i.e can be used in any java collections. |
It is not a universal cursor.i.e we can use it only for some legacy classes. |
It supports both Read and Remove operations. |
It supports only Read operation. |
It has simple method names. |
It has lengthy method names. |
One can do any modification while traversing over the elements. |
We cannot do any modifications while traversing. |
Not a legacy interface. Can traverse overall collections like ArrayList, HashMap, TreeSet, Vector etc.collections |
Legacy interface. Traverse only Vector, Hashtable. |
Methods:
Methods
|
Type |
Explanation |
hasNext() |
boolean |
- If iteration has more elements, then it returns true.
- If the iterator has gone through all the elements, it returns false
|
next() |
E |
- It returns the next element of iteration.
- It throws NoSuchElementException if the iterator has no more elements.
|
remove() |
void |
- 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.
|
forEachRemaining() |
E |
- 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.
|
Similar Reads
Iterable Interface in Java
The Iterable interface was introduced in JDK 1.5. It belongs to java.lang package. In general, an object Implementing Iterable allows it to be iterated. An iterable interface allows an object to be the target of enhanced for loop(for-each loop). Definition of Iterable public interface Iterable<T
3 min read
IntUnaryOperator Interface in Java
The IntUnaryOperator Interface is a part of the java.util.function package, which has been introduced since Java 8, to implement functional programming in Java. It represents a function that takes in one argument and operates on it. Both its argument and return type are of the int data type. It is v
3 min read
IntStream iterator() in Java
In Java, streams are used to process sequences of data efficiently. IntStream is a special type of stream which is designed to handle primitive int values. This avoids the need for converting the primitive types into objects. The iterator() method in IntStream is a terminal operation that gives us a
3 min read
Convert Iterator to Iterable in Java
Given an Iterator, the task is to convert it into Iterables in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Below are the various ways to do so: By overriding the abstract method Iterable.itera
3 min read
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface: The interface in Java is a mechanism to
13 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Example: [GFGTABS] Java //Driver Code Starts{ // A class can implement multiple interfaces import java.io.*; //Driver Code
7 min read
Java | Implementing Iterator and Iterable Interface
Iterators are used in Collection framework in Java to retrieve elements one by one. For more details and introduction related to this, see this link. Why it is needed to implement Iterable interface? Every class that implements Iterable interface appropriately, can be used in the enhanced For loop (
4 min read
Queue Interface In Java
The Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features: Most implementations, like PriorityQueue, do not allow null elements.Implementation Clas
12 min read
Deque Interface in Java
Deque Interface present in java.util package is a subtype of the queue interface. The Deque is related to the double-ended queue that supports adding or removing elements from either end of the data structure. It can either be used as a queue(first-in-first-out/FIFO) or as a stack(last-in-first-out/
10 min read
Iterator vs Collection in Java
Iterator and Collection, both has helped and comforted the programmers at many a times. But their usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iteratorIterators are used in Collection fr
3 min read