Open In App

PriorityQueue remove() Method in Java

Last Updated : 14 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The remove() method of PriorityQueue class of java.util package 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<String> = new PriorityQueue<String>(ComparatorHere);

Syntax: 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 Program to Illustrate remove() Method
// in PriorityQueue
// Where Elements are of String Type
 
// Importing all utility classes
import java.util.*;
 
// Main class
// PriorityQueueDemo
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Creating an empty PriorityQueue
        // where elements are of string type
        PriorityQueue<String> queue
            = new PriorityQueue<String>();
 
        // Adding elements into the Queue
        // using add() method
        queue.add("Welcome");
        queue.add("To");
        queue.add("Geeks");
        queue.add("For");
        queue.add("Geeks");
 
        // Printing the elements of PriorityQueue
        System.out.println("Initial PriorityQueue: "
                           + queue);
 
        // Removing elements from PriorityQueue
        // using remove() method
        queue.remove("Geeks");
        queue.remove("For");
        queue.remove("Welcome");
 
        // Displaying the PriorityQueue
        // after removal of element
        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 Program to Illustrate remove() Method
// of PriorityQueue class
// Where Elements are of Integer type
 
// Importing required classes
import java.util.*;
 
// Main class
// PriorityQueueDemo
public class GFG {
 
    // 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 custom input elements
        // using add() method
        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 from the PriorityQueue
        // using remove() method
        queue.remove(30);
        queue.remove(5);
 
        // Displaying the PriorityQueue elements
        // 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]

 

Geek, have you ever wondered 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.

Note: This class do implements AbstractQueueInterface

Example 

Java




// Java Program to illustrate remove() Method
// in PriorityQueue
// Where Exception is encountered
 
// Importing required classes
import java.io.*;
import java.util.PriorityQueue;
 
// Main class
// PriorityQueueException
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty PriorityQueue
        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 in above queue
        // using add() method
        pq.add(2);
        pq.add(14);
        pq.add(41);
        pq.add(7);
        pq.add(99);
 
        // Elements in queue are unsorted by far
 
        // Getting size of above queue before deletion
        // of any element using size() method
        System.out.println(
            "Size of priority queue before deletion : "
            + pq.size());
 
        // Printing all elements of above queue
        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:

Output explanation:

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.



Previous Article
Next Article

Similar Reads

Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
PriorityQueue toArray() Method in Java
The java.util.PriorityQueue.toArray() method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array. Syntax: Object[] arr = Priority_Queue.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array co
3 min read
PriorityQueue comparator() Method in Java
The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.Syntax: comp_set = (PriorityQueue)Priority_Queue.comparator() Parameters: Th
2 min read
PriorityQueue clear() Method in Java
The Java.util.PriorityQueue.clear() method is used to remove all the elements from a PriorityQueue. Using the clear() method only clears all the element from the queue and does not delete the queue. In other words, we can say that the clear() method is used to only empty an existing PriorityQueue. Syntax: Priority_Queue.clear() Parameters: The meth
2 min read
PriorityQueue add() Method in Java
The Java.util.PriorityQueue.add() method in Java is used to add a specific element into a PriorityQueue. This method internally just calls the Java.util.PriorityQueue.offer() method with the value passed to it. So, it exactly works like offer() method. Syntax: Priority_Queue.add(Object element) Parameters: The parameter element is of the type Prior
2 min read
PriorityQueue peek() Method in Java
The java.util.PriorityQueue.peek() method in Java is used to retrieve or fetch the first element of the Queue or the element present at the head of the Queue. The element retrieved does not get deleted or removed from the Queue. Syntax: Priority_Queue.peek() Parameters: The method does not take any parameters. Return Value: The method returns the e
2 min read
PriorityQueue iterator() Method in Java
The Java.util.PriorityQueue.iterator() method is used to return an iterator of the same elements as the Priority Queue. The elements are returned in random order from what present in the Queue. Syntax: Iterator iterate_value = Priority_Queue.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the
2 min read
PriorityQueue offer() Method in Java
The java.util.PriorityQueue.offer() method is used to insert a particular element into the Priority Queue. It acts similar to the add() method of Priority Queue. Syntax: Priority_Queue.offer(Object element) Parameters: The parameter element is of the type PriorityQueue and refers to the element to be inserted into the Queue. Return Value: The metho
2 min read
PriorityQueue contains() Method in Java
The Java.util.PriorityQueue.contains() method is used to check whether a specific element is present in the PriorityQueue or not. So basically it is used to check if a Queue contains any particular element or not. Syntax: Priority_Queue.contains(Object element) Parameters: The parameter element is of the type of PriorityQueue. This is the element t
2 min read
PriorityQueue poll() Method in Java
The java.util.PriorityQueue.poll() method in Java is used to retrieve or fetch and remove the first element of the Queue or the element present at the head of the Queue. The peek() method only retrieved the element at the head but the poll() also removes the element along with the retrieval. It returns NULL if the queue is empty. Syntax: Priority_Q
2 min read
PriorityQueue size() Method in Java
The Java.util.PriorityQueue.size() method is used to get the size of the PriorityQueue or the number of elements present in the PriorityQueue. Syntax: Priority_Queue.size() Parameters: This method does not takes any parameter. Return Value: The method returns the size or the number of elements present in the PriorityQueue. Below programs illustrate
2 min read
PriorityQueue spliterator() method in Java
The spliterator() method of PriorityQueue returns a Spliterator the same elements as PriorityQueue.The returned Spliterator is late-binding and fail-fast Spliterator. A late-binding Spliterator binds to the source of elements means PriorityQueue at the point of first traversal, first split, or first query for estimated size, rather than at the time
2 min read
Implement PriorityQueue through Comparator in Java
Prerequisite : Priority Queue, Comparator Priority Queue is like a regular queue, but each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. For this, it uses a comparison function which imposes a total ordering of the elements. The elements of the priority
3 min read
How can I modify an element of a PriorityQueue in Java?
A PriorityQueue is an abstract data type that is similar to a queue, and every element has some priority value associated with it. It is used when the objects are supposed to be processed based on priority. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depen
7 min read
PriorityQueue in Java
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that's when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap.
11 min read
Difference Between PriorityQueue and TreeSet
The PriorityQueue and TreeSet both are the classes defined inside the Collection Framework. In this article, we will learn the differences between PriorityQueue and TreeSet. PriorityQueue is an implementation of Queue interface and the TreeSet is the implementation of the Set interface. There are some differences exists between them. So we have tri
3 min read
TreeSet remove() Method in Java
The Java.util.TreeSet.remove(Object O) method is to remove a particular element from a Tree set. Syntax: TreeSet.remove(Object O) Parameters: The parameter O is of the type of Tree set and specifies the element to be removed from the set. Return Value: This method returns True if the element specified in the parameter is initially present in the Se
1 min read
EnumMap remove() Method in Java
The Java.util.EnumMap.remove(key) method in Java is used to remove the specified key from the map. Syntax: remove(Object key) Parameters: The method takes one parameter key which refers to the key whose mapping is to be removed. Return Value: The method does not return any value. Below programs illustrate the working of remove(key) function: Progra
2 min read
LinkedList remove() Method in Java
LinkedList as we all know is a way of storing data that contains sets of nodes where each node contains data and address part where address part is responsible for linking of nodes and hence forming a List over which now we can perform operations. Now here we want to remove a node/s using the remove() method of LinkedList class only. Illustration:
4 min read
HashSet remove() Method in Java
HashSet remove() method is used to remove a particular element from a HashSet. Note that it is only after JDK version 1.2 and ahead, and will throw compilation errors before in version JDK 1 and JDK1.1. Note: This method returns true if the specified element is present in the HashSet otherwise it returns boolean false. Syntax: HashSet.remove(Object
2 min read
HashMap remove() Method in Java
The java.util.HashMap.remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.Syntax: Hash_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map.Return Value: The
2 min read
TreeMap remove() Method in Java
The java.util.TreeMap.remove() is an inbuilt method of TreeMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Syntax: Tree_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map. Return Value: Th
2 min read
ArrayDeque remove() Method in Java
The Java.util.ArrayDeque.remove() method is used to remove the element present at the head of the Deque. Syntax: Array_Deque.remove() Parameters: The method does not take any parameters. Return Value: This method returns the element present at the head of the Deque. Exceptions: The method throws NoSuchElementException is thrown if the deque is empt
3 min read
WeakHashMap remove() method in Java
The java.util.WeakHashMap.remove() is an inbuilt method of WeakHashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Syntax: Weak_Hash_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map. Ret
2 min read
ArrayBlockingQueue remove() method in Java
ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework. Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue. The queue also follows FIFO (first-in-first-out) rule for st
3 min read
IdentityHashMap remove() Method in Java
The java.util.IdentityHashMap.remove() is an inbuilt method of IdentityHashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Syntax: Identity_Hash_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from
2 min read
Vector remove() Method in Java
remove(int index) The java.util.vector.remove(int index) method is used to remove an element from a Vector from a specific position or index. Syntax: Vector.remove(int index) Parameters: This method accepts a mandatory parameter index is of integer data type and specifies the position of the element to be removed from the Vector. Return Value: This
2 min read
LinkedBlockingQueue remove() method in Java
The remove(Object obj) method of LinkedBlockingQueue removes only one instance of the given Object, passed as parameter, from this LinkedBlockingQueue if it is present. It removes an element e such that obj.equals(e) and if this queue contains one or more instance of element e. This method returns true if this queue contained the element which is n
4 min read
PriorityBlockingQueue remove() method in Java
The remove(Object o) method of PriorityBlockingQueue is used to delete an element from this queue. This method removes a single instance of the element passed as the parameter, if it is present. It returns true if and only if the element was removed, else it returned false. Syntax: public boolean remove(Object o) Parameter: This method accepts a ma
2 min read
ConcurrentHashMap remove() method in Java
The remove() method in Java's ConcurrentHashMap class is used to remove the entry for a given key from the map. It has the following signature: V remove(Object key)where: key is the key of the entry to be removed.V is the type of values in the map.The remove() method works in a concurrent environment, which means that multiple threads can access an
7 min read
three90RightbarBannerImg