Launch your tech mastery with us—your coding journey starts now!
Course Content
Data Structure

A Priority Queue is a special type of queue where each element has a priority. Elements with higher priority are served before elements with lower priority. In Java, we can use the built-in PriorityQueue class. By default, it implements a Min-Heap (smallest element is processed first). Priority Queue data structure illustration showing elements arranged based on priority levels, with higher priority elements dequeued first and arrows indicating enqueue and dequeue operations. Java Example

import java.util.PriorityQueue;

public class PriorityQueueDemo {
    public static void main(String[] args) {
        // Min Heap (Default behavior)
        PriorityQueue minHeap = new PriorityQueue();
       
        minHeap.add(30);
        minHeap.add(10);
        minHeap.add(20);

        System.out.println("Processing Min Heap:");
        while (!minHeap.isEmpty()) {
            // poll() removes the head of the queue (smallest element)
            System.out.println(minHeap.poll());
        }
        // Output: 10, 20, 30

        // Max Heap (Custom Comparator)
        PriorityQueue maxHeap = new PriorityQueue((a, b) -> b - a);
       
        maxHeap.add(30);
        maxHeap.add(10);
        maxHeap.add(20);

        System.out.println("\nProcessing Max Heap:");
        while (!maxHeap.isEmpty()) {
            System.out.println(maxHeap.poll());
        }
        // Output: 30, 20, 10
    }
}