Write a Java program to retrieve an element from the head of the queue without removing it


The Java code demonstrates how to use the Queue interface with the LinkedList class to add elements to a queue and retrieve the element at the head of the queue without removing it using the peek() method. The peek() method returns the head element of the queue, or null if the queue is empty.

  • A Queue interface is implemented using the LinkedList class to create a queue to store strings.
  • Several elements ("Orange", "Yellow", "Green", "Pink", "Black", "Blue", "White", "Red") are added to the queue using the add() method.
  • The current elements in the queue are printed using System.out.println().
  • The peek() method is used to retrieve the element at the head of the queue without removing it. The value is stored in the headElement variable.
  • The element at the head of the queue is printed.
  • The current elements in the queue after peeking are printed again.

Source Code

import java.util.LinkedList;
import java.util.Queue;
public class RetrieveElement
{
	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.println("Queue Elements : "+queue_list);
 
		// Retrieve the element at the head of the queue without removing it using peek()
		String headElement = queue_list.peek();
 
		System.out.println("Element at the head of the Queue : " + headElement);
		System.out.println("Queue after peek : " + queue_list);
	}
}

Output

Queue Elements : [Orange, Yellow, Green, Pink, Black, Blue, White, Red]
Element at the head of the Queue : Orange
Queue after peek : [Orange, Yellow, Green, Pink, Black, Blue, White, Red]

Example Programs