Write a Java program to Remove all Duplicate elements from the queue


The Java code defines a class RemoveDuplicates with a method removeDuplicates that removes duplicates from a given Queue of integers.

  • The removeDuplicates method takes a Queue<Integer> named queue as input and removes duplicates from the queue.
  • It creates a Set<Integer> named uniqueElements to store the unique elements encountered in the queue.
  • It also calculates the initial size of the queue using the size() method.
  • The method uses a loop to iterate size times to process each element in the queue.
  • In each iteration, the element is dequeued from the front of the queue using poll() and stored in the variable element.
  • The method checks if uniqueElements already contains the current element. If it does not contain the element, it means the element is unique. In this case, the element is enqueued back into the queue using offer(), and it is added to the uniqueElements set using add().
  • If the element is already in the uniqueElements set (i.e., it's a duplicate), it will not be enqueued back into the queue, effectively removing the duplicate from the queue.
  • After the loop finishes, the queue will have duplicates removed, and it will only contain unique elements in their original order.
  • In the main method, a Queue<Integer> named queue is created using the LinkedList implementation of the Queue interface. Integers are added to the queue using the offer() method.
  • The original queue is printed using System.out.println().
  • The removeDuplicates method is then called with the queue as an argument, and the duplicates are removed from the queue.
  • Finally, the queue after removing duplicates is printed using System.out.println().

Source Code

import java.util.*;
 
public class RemoveDuplicates
{
	public static void removeDuplicates(Queue<Integer> queue)
	{
		Set<Integer> uniqueElements = new HashSet<>();
		int size = queue.size();
 
		for (int i = 0; i < size; i++)
		{
			int element = queue.poll();
			if (!uniqueElements.contains(element))
			{
			queue.offer(element);
			uniqueElements.add(element);
			}
		}
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(1);
		queue.offer(2);
		queue.offer(2);
		queue.offer(3);
		queue.offer(3);
		queue.offer(3);
		queue.offer(4);
		queue.offer(4);
		queue.offer(4);
		queue.offer(4);
		queue.offer(5);
		queue.offer(5);
		queue.offer(5);
		queue.offer(5);
		queue.offer(5);
 
		System.out.println("Original Queue: " + queue);
		removeDuplicates(queue);
		System.out.println("Queue after removing duplicates: " + queue);
	}
}
 

Output

Original Queue: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
Queue after removing duplicates: [1, 2, 3, 4, 5]

Example Programs