PriorityQueue in Java
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Java PriorityQueue provides a built-in priority heap supporting fast insertion, inspection, and retrieval of highest-priority elements.
Default min heap behaviour and core API
PriorityQueue is the Java class that stores elements in a binary heap, so poll returns the smallest element by default, or the one a Comparator ranks first.
The java.util.PriorityQueue class is an unbounded priority queue based on an array-backed binary heap. By default, elements are ordered according to their natural ordering using Comparable. Therefore, the smallest element always sits at the head of the queue.
Example 1 · Min-Heap Default and Max-Heap with Comparator
import java.util.Collections;import java.util.PriorityQueue;
public class Main { public static void main(String[] args) { // Default Min-Heap PriorityQueue<Integer> minPq = new PriorityQueue<>(); minPq.offer(40); minPq.offer(10); minPq.offer(25); System.out.println("Min-heap poll: " + minPq.poll());
// Max-Heap via Collections.reverseOrder() PriorityQueue<Integer> maxPq = new PriorityQueue<>(Collections.reverseOrder()); maxPq.offer(40); maxPq.offer(10); maxPq.offer(25); System.out.println("Max-heap poll: " + maxPq.poll()); }}Min-heap poll: 10 Max-heap poll: 40
What this code does
- minPq extracts the smallest number 10 first by default.
- maxPq uses Collections.reverseOrder() to extract the largest number 40 first.
- Both poll operations execute in logarithmic O(log n) time.
The primary methods are offer or add, poll, peek, and size. The offer and add methods insert an element and sift it up in O(log n) time. The peek method inspects the minimum element at the head in constant O(1) time. The poll method retrieves and removes the head in O(log n) time, returning null if empty. PriorityQueue does not permit null elements. Attempting to insert a null value triggers an immediate NullPointerException.
Trace the code
Watch offer, peek and poll
Step through a small PriorityQueue program.
Variables
- pq
- []
Output
(nothing printed yet)Line 5An empty min-heap is created.
Creating max heaps and ordering custom objects
To reverse the default ordering and create a max-heap, supply a custom Comparator to the constructor. Passing Collections.reverseOrder produces a max-heap where poll yields the largest element first.
Example 2 · Custom Object Priority with Multi-Level Comparator
import java.util.Comparator;import java.util.PriorityQueue;
public class Main { static class Patient { String name; int severity; // Higher is more urgent int arrivalOrder;
Patient(String name, int severity, int arrivalOrder) { this.name = name; this.severity = severity; this.arrivalOrder = arrivalOrder; } }
public static void main(String[] args) { Comparator<Patient> comp = Comparator .comparingInt((Patient p) -> p.severity).reversed() .thenComparingInt(p -> p.arrivalOrder);
PriorityQueue<Patient> er = new PriorityQueue<>(comp); er.offer(new Patient("Alice", 2, 1)); er.offer(new Patient("Bob", 5, 2)); er.offer(new Patient("Charlie", 5, 3)); er.offer(new Patient("Dave", 1, 4));
while (!er.isEmpty()) { Patient p = er.poll(); System.out.println(p.name + " (Severity " + p.severity + ", Arrival " + p.arrivalOrder + ")"); } }}Bob (Severity 5, Arrival 2) Charlie (Severity 5, Arrival 3) Alice (Severity 2, Arrival 1) Dave (Severity 1, Arrival 4)
What this code does
- Patients with highest severity are served first.
- Ties in severity resolve in favor of earlier arrival order.
- Comparator cleanly chains primary and secondary sorting rules.
For user-defined domain classes, you can either implement the Comparable interface or provide a lambda comparator. Consider a Task class with urgency and arrival timestamp fields. A priority queue can prioritize tasks by highest urgency first. When two tasks share the same urgency, tie-breakers can order by earlier arrival timestamp. Java Comparator.comparing paired with thenComparing constructs clean multi-level priority rules in readable code.
Find the bug
Find the PriorityQueue bug
Each snippet uses a PriorityQueue. Tap the wrong line.
This should print the largest value, 9.
Round 1 of 3Iteration order pitfall and mutating elements
A frequent beginner trap occurs when iterating over a PriorityQueue using an enhanced for-loop or Iterator. The iterator traverses the underlying array directly in level order without sorting. Therefore, printing elements with a for-each loop does not display elements in priority sequence.
Example 3 · Iteration Order Trap vs Poll Sequence
import java.util.PriorityQueue;
public class Main { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(50); pq.offer(10); pq.offer(30); pq.offer(20); pq.offer(40);
System.out.print("For-each traversal: "); for (int v : pq) { System.out.print(v + " "); } System.out.println();
System.out.print("Poll extraction: "); while (!pq.isEmpty()) { System.out.print(pq.poll() + " "); } System.out.println(); }}For-each traversal: 10 20 30 50 40 Poll extraction: 10 20 30 40 50
What this code does
- For-each iterates over the underlying heap array, which is not fully sorted.
- poll() repeatedly extracts the root and restores invariant, yielding sorted order.
- Never rely on iteration order when processing PriorityQueue elements.
To process elements in true prioritized order, repeatedly call poll until the queue is empty. Another critical trap involves modifying objects already stored inside the queue. Changing an object field that affects its comparison order does not automatically re-heapify the structure. The queue structure becomes corrupted, leading to incorrect poll results.
Predict the output
Predict the output
Read each snippet and pick what it prints.
Round 1 of 2
Next step
Check your understanding
10 quick questions