Write a Java program to print Queue elements using foreach loop


The Java code demonstrates how to use a foreach loop to iterate through the elements of a Queue. The Queue is implemented using a LinkedList, and it contains a list of colors. The program prints all the elements in the queue using the foreach loop. Let's go through the code step-by-step:

  • A Queue of strings called queue_list is created, and a LinkedList is used as its underlying implementation.
  • Several colors are added to the queue using the add() method.
  • The message "Queue Elements: " is printed using System.out.print().
  • The for loop with a foreach loop syntax is used to iterate through the elements of queue_list.
  • Inside the foreach loop, the variable item iterates through each element of the queue, and the current item is printed along with two spaces.
  • After the loop finishes, all the elements in the queue are printed on a single line.

Source Code

import java.util.LinkedList;
import java.util.Queue;
public class QueueForeachLoop
{
	public static void main(String[] args)
	{
		Queue <String> queue_list = new LinkedList <>();
		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");
 
		System.out.print("Queue Elements : ");
 
		// Print queue elements using foreach loop
		for (String item: queue_list)
		{
			System.out.print(item + "  ");
		}
	}
}

Output

Queue Elements : Orange  Yellow  Green  Pink  Black  Blue  White  Red

Example Programs