PriorityQueue

The PriorityQueue interface in Java represents a priority queue based on the heap data structure. Unlike a regular queue, where elements are retrieved in a first-in-first-out (FIFO) manner, a priority queue retrieves elements based on their priority. The element with the highest priority is dequeued first. In Java, PriorityQueue is implemented as a priority heap, which is a binary heap where elements are ordered either by their natural ordering or by a comparator provided at the time of queue creation.

import java.util.PriorityQueue;

// Syntax for creating a PriorityQueue with natural ordering
PriorityQueue<Type> queueName = new PriorityQueue<>();Code language: JavaScript (javascript)

Methods:

  1. Adding Elements:
  • boolean offer(element): Inserts the specified element into the priority queue.
  • void add(element): Inserts the specified element into the priority queue.

     2. Removing Elements:

  • element poll(): Retrieves and removes the head of the queue (element with the highest priority).
  • element remove(): Retrieves and removes the head of the queue.
  • element peek(): Retrieves, but does not remove, the head of the queue.
  • element element(): Retrieves, but does not remove, the head of the queue.

     3.Checking Size and Empty Status

 

  • int size(): Returns the number of elements in the priority queue.
  • boolean isEmpty(): Returns true if the priority queue contains no elements.
import java.util.PriorityQueue;
public class PriorityQueueExample {
    public static void main(String[] args) {
        // Creating a PriorityQueue to store task priorities
        PriorityQueue<Integer> taskQueue = new PriorityQueue<>();

        // Adding task priorities to the PriorityQueue
        taskQueue.add(5);  // low priority task
        taskQueue.add(1);  // highest priority task
        taskQueue.add(3);  // medium priority task
        taskQueue.add(2);  // high priority task
        taskQueue.add(4);  // medium priority task

        // Displaying the priority queue
        System.out.println("PriorityQueue of tasks:");
        while (!taskQueue.isEmpty()) {
            System.out.println(taskQueue.poll());
        }

        // Checking if the priority queue is empty
        System.out.println("Is the priority queue empty? " + taskQueue.isEmpty());
    }
}
D:\>javac PriorityQueueExample.java

D:\>java PriorityQueueExample
PriorityQueue of tasks:
1
2
3
4
5
Is the priority queue empty? trueCode language: PHP (php)

PriorityQueue in Java provides a powerful tool for managing elements based on their priority levels. It ensures efficient access to the highest-priority elements and supports both natural and custom ordering criteria. Understanding how to use PriorityQueue enables developers to design efficient algorithms for priority-based processing in various applications, from task scheduling to event handling.

Scroll to Top