Java Utility Library

Java PriorityQueue - remove() Method



The java.util.PriorityQueue.remove() method is used to remove a single instance of the specified element from this queue, if it is present. Every removal of element results into reducing the queue size by one unless the queue is empty. The method returns true if and only if this queue contained the specified element.

Syntax

public boolean remove(Object obj)

Parameters

obj Specify the element which need to be removed from this queue, if present.

Return Value

Returns true if this queue changed as a result of the call.

Exception

NA.

Example:

In the example below, the java.util.PriorityQueue.remove() method is used to remove a single instance of the specified element from the given queue.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a priority queue
    PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>();

    //populating the priority queue
    PQueue.add(10);
    PQueue.add(20);
    PQueue.add(30);
    PQueue.add(40);
    PQueue.add(30);
    
    //printing the priority queue
    System.out.println("PQueue contains: " + PQueue);

    //remove a instance of 30 from the queue
    PQueue.remove(30);

    //printing the priority queue
    System.out.println("PQueue contains: " + PQueue);
  }
}

The output of the above code will be:

PQueue contains: [10, 20, 30, 40, 30]
PQueue contains: [10, 20, 30, 40]

❮ Java.util - PriorityQueue