How to Remove a Specific Element from Queue in Java(Not Priority Queue)

How to Remove a Specific Element from Queue in Java(Not Priority Queue)

How I can remove a specific element from queue in java(not priority queue).There is no functionality of removing queue.remove(object). Please help me in this.

Queue<String> queue = new LinkedList<>();
queue.add("hello");
queue.add("world");
queue.add("ranjeet");

I want to remove "world" from it.

2

3 Answers

Queue Interface

The queue interface only allows you to remove elements from the head of the queue. See the description of the API at:

()

The whole purpose of the queue data structure is to push items to the tail and remove them from the head (as a real queue works).

You should use a different data structure / collection object type.

Another option would be to remove all the items of the queue and put them in another queue (except the item you want to remove).

Finally, another would be to make your own queue implementation adding the extra method.

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.