Write a Java program to Remove all occurrences of a specific element from a queue


The Java code demonstrates how to remove all occurrences of a specific element from a queue. Let's go through the code step by step:

  • A Queue interface is implemented using the LinkedList class to create a queue named queue to store integers.
  • Several integer elements (10, 20, 30, 20, 40, 20) are added to the queue using the offer() method.
  • The original order of elements in the queue is printed using System.out.println().
  • The removeElement() method is called with the queue and the element to remove (20) as arguments. This method removes all occurrences of the specified element from the queue.
  • The queue after removing the specified element is printed using System.out.println().

The removeElement() method is responsible for removing all occurrences of the specified element from the queue. It works as follows:

  • The method first gets the current size of the queue using queue.size() and stores it in the variable size. This is necessary because we should not modify the queue while iterating over it.
  • The method then iterates through the queue using a for loop. On each iteration, the front element of the queue is removed using the poll() method and stored in the variable currentElement.
  • If the currentElement is not equal to the specified element (20 in this case), it means it's not the element we want to remove. In this case, the element is added back to the queue using the offer() method.
  • The loop continues until all elements have been processed and, at the end, the queue will contain all elements except the ones that were equal to the specified element.

Source Code

import java.util.*;
 
public class RemoveElementFromQueue
{
	public static void removeElement(Queue<Integer> queue, int element)
	{
		int size = queue.size();
		for (int i = 0; i < size; i++)
		{
			int currentElement = queue.poll();
			if (currentElement != element)
			{
				queue.offer(currentElement);
			}
		}
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(10);
		queue.offer(20);
		queue.offer(30);
		queue.offer(20);
		queue.offer(40);
		queue.offer(20);
 
		System.out.println("Original Queue : " + queue);
		int elementToRemove = 20;
		removeElement(queue, elementToRemove);
		System.out.println("Queue after removing " + elementToRemove + " : " + queue);
	}
}
 

Output

Original Queue : [10, 20, 30, 20, 40, 20]
Queue after removing 20 : [10, 30, 40]

Example Programs