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.
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); } }
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]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions