The Java code demonstrates how to use the Queue interface with the LinkedList class to add elements to a queue and access 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 RemoveElement { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); queue.offer("Blue"); queue.offer("White"); queue.offer("Black"); queue.offer("Orange"); queue.offer("Pink"); queue.offer("Yellow"); System.out.println("Queue Elements : "+queue); // Access the element at the head of the queue using peek() String headElement = queue.peek(); if (headElement != null) { System.out.println("Element at the head of the Queue : " + headElement); } else { System.out.println("The queue is Empty"); } } }
Queue Elements : [Blue, White, Black, Orange, Pink, Yellow] Element at the head of the Queue : Blue
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions