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

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



Reffered: https://www.geeksforgeeks.org


Java

Related
How to Handle an IOException in Java? How to Handle an IOException in Java?
How to Create Symbolic Links and Hard Links in Java? How to Create Symbolic Links and Hard Links in Java?
How to Check if a PriorityQueue is Empty or Contains Elements in Java? How to Check if a PriorityQueue is Empty or Contains Elements in Java?
How to Handle NULL Values in JDBC? How to Handle NULL Values in JDBC?
How to Customize the Ordering of Elements in a PriorityQueue Using a Comparator in Java? How to Customize the Ordering of Elements in a PriorityQueue Using a Comparator in Java?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13