How to Remove the Top Element From a PriorityQueue in Java?
Last Updated :
15 Feb, 2024
A priority queue is a specialized type of queue, in which elements are given with priorities, and those with more priorities are served before elements with lower priorities. It’s equivalent to a regular queue (first-in, first-out) but prioritizes urgency rather than arrival order.
Remove the Top Element from a PriorityQueue
In Java, we can remove the top element (element with the highest priority) from a PriorityQueue using the poll() method. This method removes and returns the highest priority element from the queue.
Syntax:
public E poll()
Program to Remove the Top Element(highest priority) From a PriorityQueue
Here is the implementation:
Java
import java.io.*;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args)
{
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add( 5 );
pq.add( 10 );
pq.add( 1 );
pq.add( 20 );
System.out.println( "PriorityQueue before removal: " + pq);
int top = pq.poll();
System.out.println( "Removed element: " + top);
System.out.println( "PriorityQueue after removal: " + pq);
}
}
|
Output
PriorityQueue before removal: [1, 10, 5, 20]
Removed element: 1
PriorityQueue after removal: [5, 10, 20]
Explaination of the above Program:
- Create a PriorityQueue
- Add Elements to the PriorityQueue
- Remove the Top Element (Highest Priority)
- Print the Removed Element
- Print PriorityQueue after Removal
Share your thoughts in the comments
Please Login to comment...