Skip to content
Related Articles

Related Articles

Improve Article

PriorityQueue remove() Method in Java

  • Difficulty Level : Medium
  • Last Updated : 08 Jun, 2021

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.

Syntax:

PriorityQueue<Integer,String> = new PriorityQueue<Integer,String>(ComparatorHere);

Syntax of remove method:  

Priority_Queue.remove(Object O)

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.



Example 1:

Java




// Java code to illustrate remove() method in PriorityQueue
// where the elements are of string type
 
// Importing all utility classes
import java.util.*;
 
// Main class
public class PriorityQueueDemo {
 
    // Main driver method
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue<String> queue
            = new PriorityQueue<String>();
 
        // Use add() method to add elements into the Queue
        queue.add("Welcome");
        queue.add("To");
        queue.add("Geeks");
        queue.add("For");
        queue.add("Geeks");
 
        // Displaying the PriorityQueue
        System.out.println("Initial PriorityQueue: "
                           + queue);
 
        // Removing elements using remove() method
        queue.remove("Geeks");
        queue.remove("For");
        queue.remove("Welcome");
 
        // Displaying the PriorityQueue after removal
        System.out.println("PriorityQueue after removing "
                           + "elements: " + queue);
    }
}

 
 

Output
Initial PriorityQueue: [For, Geeks, To, Welcome, Geeks]
PriorityQueue after removing elements: [Geeks, To]

 

Example 2:

 

Java




// Java code to illustrate remove() method in PriorityQueue
// Where Elements are of Integer type
 
// Importing utility classes
import java.util.*;
 
// Main class
public class PriorityQueueDemo {
 
    // Main driver method
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue by
        // creating an object of integer type
        PriorityQueue<Integer> queue
            = new PriorityQueue<Integer>();
 
        // Adding elements into the Queue
        // using add() method
 
        // Custom input integer entries
        queue.add(10);
        queue.add(15);
        queue.add(30);
        queue.add(20);
        queue.add(5);
 
        // Displaying the PriorityQueue
        System.out.println("Initial PriorityQueue: "
                           + queue);
 
        // Removing elements using remove() method
        queue.remove(30);
        queue.remove(5);
 
        // Displaying the PriorityQueue after removal
        System.out.println("PriorityQueue after removing "
                           + "elements: " + queue);
    }
}

 
 

Output: 



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:

 

Example:

 

Java




// Java Program to illustrate remove() method in PriorityQueue
// Where Exception is encountered
 
// Importing PriorityQueue class from java.util package
// Note: This class do implements AbstractQueueInterface
 
// Importing PriorityQueue class from java.util package
import java.io.*;
import java.util.PriorityQueue;
 
// Main class
class PriorityQueueException {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a priority queue
        PriorityQueue<Integer> pq
            = new PriorityQueue<Integer>();
 
        // Note: Elements are inserted in unsorted order in
        // priority queue but after removal of elements queue
        // is always sorted.
 
        // Adding elements
        pq.add(2);
        pq.add(14);
        pq.add(41);
        pq.add(7);
        pq.add(99);
 
        // Elements in queue are unsorted by far
        System.out.println(
            "Size of priority queue before deletion : "
            + pq.size());
        System.out.println(
            "Priority queue before removal : " + pq);
 
        // Calling remove() method over priority queue
        // in which there were 5 elements
 
        // Here calling remove() method say be it 2 times
        // So 2 top priority elements will be removed
        System.out.println(" 1st element removed : "
                           + pq.remove());
        System.out.println(" 2nd element removed : "
                           + pq.remove());
        System.out.println(" 3rd element removed : "
                           + pq.remove());
        System.out.println(" 4th element removed : "
                           + pq.remove());
        System.out.println(" 5th element removed : "
                           + pq.remove());
 
        // By now queue is empty and if now we made further
        // remove() call it will throw exception for this
        System.out.println(" 6th element removed : "
                           + pq.remove());
 
        // As we know smaller the integer bigger the
        // priority been set by default comparator of this
        // class.
 
        // Note: Now the element is always returned sorted
        // from a priority queue is a trait of this class
 
        // Printing the queue after removal of priority
        // elements
        System.out.println(
            "Priority queue after removal as follows: "
            + pq);
    }
}

Output:

Exception in thread “main” java.util.NoSuchElementException 
at java.base/java.util.AbstractQueue.remove(AbstractQueue.java:117) 
at PriorityQueueException.main(File.java:59)
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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :