PriorityQueue remove() Method in Java
The Java.util.PriorityQueue.remove() method is used to remove a particular element from a PriorityQueue. As we all know that the elements while entering into the priority queue are not sorted but as we all know while taking out elements from the priority queue the elements are always sorted being a trait of the priority queue. Here the default ordering of priority of elements for data types is defined as follows:
- Integer: Smallest elements that come first (while dealing with positive numbers only)
- String: Alphabetical ordering
Note: We can also insert a Comparator while creating an instance of this class which tells us how the priority should be defined.
PriorityQueue<Integer,String> = new PriorityQueue<Integer,String>(ComparatorHere);
Syntax of remove method:
Parameters: The parameter O is of the type of PriorityQueue and specifies the element to be removed from the PriorityQueue.
Return Value: This method returns True if the specified element is present in the Queue else it returns False.
Initial PriorityQueue: [For, Geeks, To, Welcome, Geeks] PriorityQueue after removing elements: [Geeks, To]
Initial PriorityQueue: [5, 10, 30, 20, 15] PriorityQueue after removing elements: [10, 20, 15]
Exception: Ever wonder what will happen if calls of remove() method exceed the elements present in the queue. In this scenario, it will continue to remove the elements that were there, and thereafter it will not find any element to remove priority wise, so it will throw an exception which is as follows:
Exception in thread “main” java.util.NoSuchElementException
Size of priority queue before deletion : 5
Priority queue before removal : [2, 7, 41, 14, 99]
1st element removed : 2
2nd element removed : 7
3rd element removed : 14
4th element removed : 41
5th element removed : 99
It is showcasing that there are no further elements left in the queue as a queue is empty by now so does it throw NoSuchElementException.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.