In this shot, we will learn how to use the PriorityQueue.remove()
method in Java.
The PriorityQueue.remove()
method is used to remove the single instance of a particular element from the PriorityQueue
.
The PriorityQueue.remove()
method is present in the PriorityQueue
class inside the java.util
package.
The syntax of the method is given below:
public boolean remove(E element);
The PriorityQueue.remove()
method accepts one parameter:
Element
: The element whose instance is to be removed from the PriorityQueue
.The PriorityQueue.remove()
method returns a boolean value:
True
: The specified element is present in the PriorityQueue
.False
: The specified element is not present in the PriorityQueue
.Let’s look at the code below.
import java.util.*;class Main{public static void main(String[] args){PriorityQueue<Integer> pq = new PriorityQueue<Integer>();pq.add(2);pq.add(28);pq.add(6);pq.add(80);pq.add(28);pq.add(7);pq.add(15);System.out.println("Original priority queue is: " + pq);boolean element_removed = pq.remove(28);if (element_removed)System.out.println("Element removed.");elseSystem.out.println("Element is not removed.");element_removed = pq.remove(78);if (element_removed)System.out.println("Element removed.");elseSystem.out.println("Element is not removed.");System.out.println("The priority queue after removing the element = 28 is: " + pq);}}
Line 1: We import the required package.
Line 2: We create the Main
class.
Line 4: We define the main()
method.
Line 6: We declare a PriorityQueue
that consists of Integer type elements.
Lines 8 to 14: We use the PriorityQueue.add()
method to insert the elements in the PriorityQueue
.
Line 16: We print the elements present in the priority queue.
Line 18: We call the remove()
method and pass the element that needs to be removed.
Lines 20 to 23: We check whether the element was removed or not and print the message accordingly.
Line 25: We call the remove()
method again and pass a different element that needs to be removed.
Lines 27 to 30: We check whether the element was removed or not and print the message accordingly.
Line 32: We print the elements present after applying the remove()
method on the priority queue.