In this tutorial, we will learn about the Java Iterator interface with the help of an example.
The Iterator interface of the Java collections framework allows us to access elements of a collection. It has a subinterface ListIterator.
Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework.
Iterator object can be created by calling iterator() method present in Collection interface.
// Java program to demonstrate Iterator
import java.util.ArrayList;
import java.util.Iterator;
public class Test
{
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
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);
}
}
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]
Methods | Description |
---|---|
forEachRemaining(Consumer<? super E>action) | Performs the given action on each of the element until and unless all the elements have been processed or unless an exception is thrown by the action. |
hasNext() | Returns a true value if the more number of elements are encountered during iteration. |
next() | Returns the next specified element during the iteration. |
remove() | Removes the last element from the collection as provided by the iterator. |