Skip to content
Home Java PriorityQueue in Java

PriorityQueue in Java

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Collections → Topic 10 of 21
Java PriorityQueue explained — min-heap behaviour, custom Comparator, max-heap, use in Dijkstra's algorithm, and the difference between PriorityQueue and TreeSet.
⚙️ Intermediate — basic Java knowledge assumed
In this tutorial, you'll learn
Java PriorityQueue explained — min-heap behaviour, custom Comparator, max-heap, use in Dijkstra's algorithm, and the difference between PriorityQueue and TreeSet.
  • Java PriorityQueue is a min-heap — poll() returns the smallest element.
  • Use Comparator.reverseOrder() for a max-heap; use Comparator.comparing() for custom objects.
  • Iteration order is NOT sorted — only poll() respects the heap ordering.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Java's PriorityQueue is a min-heap by default — poll() returns the smallest element. Pass a Comparator to change the ordering. It is not sorted in iteration order — only poll() and peek() respect the heap property. Use PriorityQueue(Comparator.reverseOrder()) for a max-heap.

Basic Min-Heap Usage

Example · JAVA
12345678910111213141516171819202122232425262728293031323334
package io.thecodeforge.java.collections;

import java.util.PriorityQueue;

public class PriorityQueueBasics {
    public static void main(String[] args) {
        // Min-heap by default
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        minHeap.add(5);
        minHeap.add(1);
        minHeap.add(9);
        minHeap.add(3);
        minHeap.add(7);

        System.out.println("peek: " + minHeap.peek());  // 1 — smallest, no removal

        // poll() removes and returns the smallest
        while (!minHeap.isEmpty()) {
            System.out.print(minHeap.poll() + " ");
        }
        // 1 3 5 7 9 — ascending order

        System.out.println();

        // Max-heap using Comparator.reverseOrder()
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
        maxHeap.addAll(java.util.List.of(5, 1, 9, 3, 7));

        while (!maxHeap.isEmpty()) {
            System.out.print(maxHeap.poll() + " ");
        }
        // 9 7 5 3 1 — descending order
    }
}
▶ Output
peek: 1
1 3 5 7 9
9 7 5 3 1

Custom Objects with Comparator

Example · JAVA
1234567891011121314151617181920212223242526
package io.thecodeforge.java.collections;

import java.util.PriorityQueue;

public class TaskScheduler {

    record Task(String name, int priority, long deadline) {}

    public static void main(String[] args) {
        // Order by priority ascending (1 = most urgent)
        PriorityQueue<Task> queue = new PriorityQueue<>(
            Comparator.comparingInt(Task::priority)
                      .thenComparingLong(Task::deadline)
        );

        queue.add(new Task("Deploy fix",       1, 1700000000L));
        queue.add(new Task("Write tests",      3, 1700001000L));
        queue.add(new Task("Code review",      2, 1700000500L));
        queue.add(new Task("Fix critical bug", 1, 1699999000L));

        while (!queue.isEmpty()) {
            Task t = queue.poll();
            System.out.printf("[%d] %s%n", t.priority(), t.name());
        }
    }
}
▶ Output
[1] Fix critical bug
[1] Deploy fix
[2] Code review
[3] Write tests

Dijkstra's Shortest Path — Classic PriorityQueue Use

Example · JAVA
1234567891011121314151617181920212223242526272829303132
package io.thecodeforge.java.collections;

import java.util.*;

public class Dijkstra {
    // Finds shortest distances from source to all nodes
    static int[] shortestPaths(int[][] graph, int src) {
        int n = graph.length;
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[src] = 0;

        // Min-heap: [distance, node]
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
        pq.offer(new int[]{0, src});

        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int d = curr[0], u = curr[1];

            if (d > dist[u]) continue;  // stale entry

            for (int v = 0; v < n; v++) {
                if (graph[u][v] > 0 && dist[u] + graph[u][v] < dist[v]) {
                    dist[v] = dist[u] + graph[u][v];
                    pq.offer(new int[]{dist[v], v});
                }
            }
        }
        return dist;
    }
}
▶ Output
// Core of Dijkstra — PriorityQueue makes it O((V+E) log V)

🎯 Key Takeaways

  • Java PriorityQueue is a min-heap — poll() returns the smallest element.
  • Use Comparator.reverseOrder() for a max-heap; use Comparator.comparing() for custom objects.
  • Iteration order is NOT sorted — only poll() respects the heap ordering.
  • poll() removes and returns the head; peek() returns without removing; offer()/add() inserts.
  • PriorityQueue does not allow null elements — it will throw NullPointerException.

Interview Questions on This Topic

  • QHow do you create a max-heap using Java's PriorityQueue?
  • QWhat is the time complexity of PriorityQueue.poll()?
  • QWhy does iterating a PriorityQueue not yield elements in sorted order?

Frequently Asked Questions

Why does iterating over a PriorityQueue not give sorted output?

A heap is not a sorted array — it only guarantees that the root is the minimum. The rest of the array satisfies the heap property but is not in sorted order. To get sorted output, repeatedly call poll() until the queue is empty, or copy to a list and sort.

What is the difference between PriorityQueue and TreeSet?

PriorityQueue allows duplicates and is faster for insert/delete (O(log n) with a smaller constant). TreeSet does not allow duplicates, supports range queries (first(), last(), headSet()), and iterates in sorted order. For a priority queue use case, PriorityQueue is almost always better.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousLinkedHashMap and LinkedHashSetNext →Comparable and Comparator in Java
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged