Write a Java program to iterate Queue elements using the iterator() method


The Java code defines a class named IteratorMethod that demonstrates how to use an iterator to traverse a queue and print its elements. Here's a step-by-step explanation of the code:

  • Import statements: The code imports the necessary classes from the java.util package to work with queues and iterators.
  • IteratorMethod class: This is the main class that contains the main method.
  • Queue instantiation: The code creates a Queue named queue_list using the LinkedList class.
  • Adding elements to the queue: The code adds several string elements to the queue_list using the add method.
  • Obtaining an iterator: The code obtains an iterator for the queue using the iterator() method of the LinkedList class. The iterator is of type Iterator<String>.
  • Iterating through the queue: The code prints a message indicating that it is going to iterate through the queue. Then it enters a while loop that checks if the iterator has a next element using the hasNext() method. If there is a next element, it retrieves it using the next() method and stores it in the variable ele. Then it prints the ele.
  • Printing the queue elements: The code prints a message before entering the loop to indicate that it is going to print the queue elements.

Source Code

import java.util.*;
public class IteratorMethod
{
	public static void main(String[] args)
	{
		Queue <String> queue_list = new LinkedList<>();
 
		// Adding elements to the queue
		queue_list.add("Orange");
		queue_list.add("Yellow");
		queue_list.add("Green");
		queue_list.add("Pink");
		queue_list.add("Black");
		queue_list.add("Blue");
		queue_list.add("White");
		queue_list.add("Red");
 
		// Obtaining an iterator for the queue
                Iterator<String> iterator = queue_list.iterator();
 
		// Iterating through the queue elements using the iterator
		System.out.println("Queue Elements :");
 
		while (iterator.hasNext())
		{
			String ele = iterator.next();
			System.out.println(ele);
		}
	}
}

Output

Queue Elements :
Orange
Yellow
Green
Pink
Black
Blue
White
Red

Example Programs