Iterator in java

Iterator is a interface in java, help you to traverse the element of collection.

Iterator in java

Iterator is a interface in java, help you to traverse the element of collection.

Iterator in java

Iterator in java

In this section you will learn about Iterator in java.  In order to cycle through the element of collection, iterator is used. For example, iterator can be used to display the element of collection. Iterator enables removing or fetching element from the collection. Iterator replace enumeration in java collection.

Iterator in java, is traversing the object from collection. As we know, for loop, for-each loop and while loop, they all are traversed based on index but Iterator in java is to traverse through object as well as accessing data from collection. Java Iterator is an interface that belongs to collection and allows iterate through the element of collection. It comes under java.util package as a public interface Iterator. It has three methods, they are as follows:

  • boolean hasNext() :  Returns true if the iteration has more element.
  • Object next(): Returns the next element in the collection.
  • void remove(): Removes from the underlying collection the last element is returned by the iterator.

How to create Iterator in Java?

Every class of collection has iterator() method in java that return an iterator to the starting of collection. Using iterator object you can access the element of collection, one element at a time. To use an itearator for retrieving the data from collection, follow these steps:

  • Call  collection iterator(), iterator will be obtained at the start of collection.
  • Apply a loop that make a call to hasNext() method. as long as hasNext() return true.
  • Retrieve each element by calling next(), within the loop.

Example :  Code using iterator to display the content of queue

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class IteratorDemo {
public static void main(String args[])
	{
		        Queue qe=new LinkedList();
                        qe.add("Welcome");
		        qe.add("To");
		        qe.add("Rose");
		        qe.add("India");
		        Iterator it=qe.iterator();

		        System.out.println("Initial Capacity of Queue :"+qe.size());

		        while(it.hasNext())
		        {
		       System.out.println( it.next());    
		        }
		      }
           }

In the above code, a queue is created by using iterator object and each element of queue is displayed.

Output : After compiling and executing the above code, output will be as follows.