Write a Java program to Removing elements from the queue using poll() methods


The Java code demonstrates how to use the Queue interface with the LinkedList class to add elements to a queue and remove elements from the queue 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

  • A Queue interface is implemented using the LinkedList class to create a queue to store strings.
  • Several elements ("Blue", "White", "Black", "Orange", "Pink", "Yellow") are added to the queue using the offer() method.
  • The current elements in the queue are printed using System.out.println().
  • Two elements are removed from the queue using the poll() method. The removed elements are stored in removedElement1 and removedElement2 variables.
  • The removed elements are printed.
  • The current elements in the queue after removing elements are printed again.

Source Code

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 before removing Elements : " + queue);
 
		// Remove elements from the queue using poll()
		String removedElement1 = queue.poll();
		String removedElement2 = queue.poll();
 
		System.out.println("Removed Elements : " + removedElement1 + ", " + removedElement2);
		System.out.println("Queue after removing Elements : " + queue);
    }
}

Output

Queue before removing Elements : [Blue, White, Black, Orange, Pink, Yellow]
Removed Elements : Blue, White
Queue after removing Elements : [Black, Orange, Pink, Yellow]

Example Programs