In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced in order to iterate over a collection of Java object components entirety one by one.
The Java Iterator is also known as the universal cursor of Java as it is appropriate for all the classes of the Collection framework. The Java Iterator also helps in the operations like READ and REMOVE.
Java Iterator Methods
The following figure perfectly displays the class diagram of the Java Iterator interface. It contains a total of four methods that are:
hasNext()
next()
remove()
forEachRemaining()
import java.io.*;
import java.util.*;
public class JavaIteratorExample {
public static void main(String[] args)
{
ArrayList cityNames = new ArrayList();
cityNames.add(“Delhi”);
cityNames.add(“Mumbai”);
cityNames.add(“Kolkata”);
cityNames.add(“Chandigarh”);
cityNames.add(“Noida”);
// Iterator to iterate the cityNames
Iterator iterator = cityNames.iterator();
System.out.println(“CityNames elements : “);
while (iterator.hasNext())
System.out.print(iterator.next() + ” “);
System.out.println();
}
}