Open In App

How to Remove the Top Element From a PriorityQueue in Java?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to Remove the Top
// Element From a PriorityQueue
import java.io.*;
import java.util.PriorityQueue;
  
// Driver Class
public class Main {
    public static void main(String[] args)
    {
        // Creating a PriorityQueue
        PriorityQueue<Integer> pq = new PriorityQueue<>();
  
        // Adding elements to the PriorityQueue
        pq.add(5);
        pq.add(10);
        pq.add(1);
        pq.add(20);
  
        System.out.println("PriorityQueue before removal: " + pq);
  
        // Removing the top element (highest priority) using
        // poll()
        int top = pq.poll();
        System.out.println("Removed element: " + top);
  
        // Printing the PriorityQueue after removal
        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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads