Write a Java program to retrieve & remove an element from the head of the queue


The Java code demonstrates how to use the Queue interface with the LinkedList class to add elements to a queue and retrieve elements using the poll() method. The poll() method removes and retrieves the head of the queue (the first element) if the queue is not empty. If the queue is empty, it returns null.

  • A Queue interface is implemented using the LinkedList class to create a queue to store strings.
  • Several elements ("Pink", "Blue", "Yellow", "Green", "Black", "White", "Pink", "Orange", "Red") are added to the queue using the add() method.
  • The current elements in the queue are printed using System.out.println().
  • The poll() method is used to remove and retrieve the head element ("Pink") from the queue and print it.
  • The current elements in the queue after removing the head element are printed again.

Source Code

import java.util.LinkedList;
import java.util.Queue;
public class Retrieve_Element
{
	public static void main(String[] args)
	{
		Queue <String> queue = new LinkedList <>();
 
		queue.add("Pink");
		queue.add("Blue");
		queue.add("Yellow");
		queue.add("Green");
		queue.add("Black");
		queue.add("White");
		queue.add("Pink");
		queue.add("Orange");
		queue.add("Red");
 
		System.out.println("Queue Elements : "+queue);
 
		System.out.println("Removed Element : " + queue.poll());
 
		System.out.println("Queue Elements : "+queue);
	}
}

Output

Queue Elements : [Pink, Blue, Yellow, Green, Black, White, Pink, Orange, Red]
Removed Element : Pink
Queue Elements : [Blue, Yellow, Green, Black, White, Pink, Orange, Red]

Example Programs