PriorityQueue: always the smallest first
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A PriorityQueue does not serve values in arrival order. Every poll() returns the value with the highest priority, which by default means the smallest value.
Smallest first, not first in
PriorityQueue is a Java queue that always gives you the value with the highest priority next, not the oldest one. By default the smallest value has the highest priority.
A PriorityQueue is used like any queue, but poll returns the most urgent value, not the oldest one. The example below offers numbers in a mixed order and polls them out.
Example 1 · poll always gives the smallest
import java.util.PriorityQueue;import java.util.Queue;
public class PriorityBasicsDemo { public static void main(String[] args) { Queue<Integer> pq = new PriorityQueue<>(); int[] arrivals = { 45, 12, 78, 5, 33, 20 }; for (int x : arrivals) { pq.offer(x); }
System.out.println("Printed: " + pq); System.out.println("peek: " + pq.peek());
System.out.print("poll order:"); while (!pq.isEmpty()) { System.out.print(" " + pq.poll()); } System.out.println(); }}Printed: [5, 12, 20, 45, 33, 78] peek: 5 poll order: 5 12 20 33 45 78
What this code does
- The printed form is the heap's array: 5 is first and each parent is smaller than its children, but 45 comes before 33. It is not sorted.
- Each
poll()removes the current smallest and repairs the heap, so polling everything gives fully sorted order.
In a hospital emergency room, a patient with a heart attack is seen before a patient with a sprained ankle, even if the ankle patient came earlier. The order depends on priority, not on arrival. A PriorityQueue works like that. You use it like any queue: offer to add, poll to take the next value, peek to look at it. The difference is which value is next. By default it is the smallest by natural order: the lowest number, or the string that comes first alphabetically.
Typical uses: task schedulers (most urgent task first), emergency triage, "top 10" lists, and route-finding programs such as maps apps.
How it works: a heap
A min-heap is a tree stored in an array where every parent is smaller than or equal to its children, so the smallest value is always at index 0. A PriorityQueue is built on this heap.
Inside, a PriorityQueue is a binary heap stored in an array. The code below offers five numbers, prints the queue and its smallest value, then polls everything out.
import java.util.*;
public class HeapOrder { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int x : new int[] {50, 20, 40, 10, 30}) { pq.offer(x); } System.out.println(pq + " peek: " + pq.peek()); while (!pq.isEmpty()) { System.out.println(pq.poll()); } }}[10, 20, 40, 50, 30] peek: 10 10 20 30 40 50
Picture a family tree where every parent is smaller than or equal to its two children. The smallest value is always at the very top, at index 0. peek() just reads index 0, so it is O(1). offer and poll move one value up or down the tree to repair it, which takes O(log n) steps. That is much cheaper than sorting the whole list after every change.
The heap is only partly sorted: a parent is smaller than its children, but nothing is promised between cousins. So printing the queue, or walking it with for-each, does not show sorted order. Only repeated poll() gives the values in priority order.
Predict the output
Printing order or poll order?
The same five numbers are offered in this order: 8, 3, 5, 1, 2.
Round 1 of 2
What does this print?
contains(x) and remove(x) have to search the whole array, so they are O(n). A priority queue is built for offer, peek and poll.Choosing the order
Comparator-ordered priority means a Comparator decides which value counts as first: the value it ranks lowest is polled first. With no Comparator, the natural order of the values is used.
Pass a Comparator to the constructor to change what "highest priority" means. The examples below put the largest value first, then rank patients by severity.
Example 2 · Biggest first with reverseOrder
import java.util.Comparator;import java.util.PriorityQueue;
public class AuctionDemo { public static void main(String[] args) { PriorityQueue<Integer> bids = new PriorityQueue<>(Comparator.reverseOrder()); bids.offer(15000); bids.offer(22000); bids.offer(18500); bids.offer(22000); bids.offer(9000);
System.out.println("Highest bid: Rs. " + bids.peek()); System.out.println("Top three:"); for (int i = 1; i <= 3; i++) { System.out.println(" " + i + ". Rs. " + bids.poll()); } System.out.println("Bids left: " + bids.size()); }}Highest bid: Rs. 22000 Top three: 1. Rs. 22000 2. Rs. 22000 3. Rs. 18500 Bids left: 2
What this code does
Comparator.reverseOrder()flips the natural order, so the largest bid has the highest priority: a max-heap.- Both bids of 22000 are kept. A priority queue allows duplicates, unlike a
TreeSet.
Example 3 · Hospital emergency triage
import java.util.Comparator;import java.util.PriorityQueue;
record Patient(String name, int severity, int token) {}
public class TriageDemo { public static void main(String[] args) { Comparator<Patient> urgentFirst = Comparator.comparingInt((Patient p) -> p.severity()) .reversed() .thenComparingInt(p -> p.token());
PriorityQueue<Patient> er = new PriorityQueue<>(urgentFirst); er.offer(new Patient("Ramesh (sprained ankle)", 2, 1)); er.offer(new Patient("Lakshmi (chest pain)", 9, 2)); er.offer(new Patient("Arif (high fever)", 5, 3)); er.offer(new Patient("Divya (deep cut)", 5, 4)); er.offer(new Patient("Gopal (breathing trouble)", 9, 5));
while (!er.isEmpty()) { Patient p = er.poll(); System.out.println("Token " + p.token() + ", severity " + p.severity() + ": " + p.name()); } }}Token 2, severity 9: Lakshmi (chest pain) Token 5, severity 9: Gopal (breathing trouble) Token 3, severity 5: Arif (high fever) Token 4, severity 5: Divya (deep cut) Token 1, severity 2: Ramesh (sprained ankle)
What this code does
- Higher severity comes first because of
reversed(). Ramesh came first but waits longest, because his case is the least urgent. - Among equal severities, the token number decides, so Lakshmi (token 2) is seen before Gopal (token 5). Without this tie-breaker the queue might serve them in either order.
new PriorityQueue<>(Comparator.reverseOrder()) puts the largest value first, which is called a max-heap. For your own objects, pass a comparator such as Comparator.comparingInt((Patient p) -> p.severity()). Unlike a TreeSet, a priority queue keeps duplicates: two patients with the same severity are both stored. But it does not remember who came first among equal priorities. If arrival order matters for ties, add a tie-breaker such as a token number with thenComparingInt.
The usual rules for comparing apply: no null values, and objects that are not Comparable need a comparator, or offer throws ClassCastException.
Top k with a small heap, and one trap
Top k problems ask for the best few values out of many. The examples below find the top 3 scores with a small heap, then show a trap when a priority changes after offer.
Example 4 · Top 3 scores with a size-3 min-heap
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.PriorityQueue;
record Score(String name, int marks) {}
public class TopThreeDemo { public static void main(String[] args) { Score[] all = { new Score("Aarav", 71), new Score("Bhavya", 94), new Score("Chetan", 58), new Score("Deepa", 88), new Score("Eshan", 97), new Score("Farah", 65), new Score("Gaurav", 90), new Score("Hina", 82) };
PriorityQueue<Score> best = new PriorityQueue<>(Comparator.comparingInt((Score s) -> s.marks())); for (Score s : all) { best.offer(s); if (best.size() > 3) { Score dropped = best.poll(); System.out.println("Dropped " + dropped.name() + " (" + dropped.marks() + ")"); } }
List<Score> podium = new ArrayList<>(); while (!best.isEmpty()) { podium.add(best.poll()); } Collections.reverse(podium); for (int i = 0; i < podium.size(); i++) { System.out.println((i + 1) + ". " + podium.get(i).name() + " " + podium.get(i).marks()); } }}Dropped Chetan (58) Dropped Aarav (71) Dropped Farah (65) Dropped Deepa (88) Dropped Hina (82) 1. Eshan 97 2. Bhavya 94 3. Gaurav 90
What this code does
- The heap never holds more than 3 scores. When a 4th arrives,
pollremoves the smallest of the four, so only the best 3 so far survive. - Polling the final heap gives the podium from 3rd to 1st, so
Collections.reverseturns it into 1st to 3rd.
Example 5 · Trap: changing a priority after offer
import java.util.Comparator;import java.util.PriorityQueue;
class Task { final String name; int priority;
Task(String name, int priority) { this.name = name; this.priority = priority; }}
public class ChangedPriorityDemo { public static void main(String[] args) { PriorityQueue<Task> tasks = new PriorityQueue<>(Comparator.comparingInt((Task t) -> t.priority)); Task report = new Task("Submit lab report", 5); tasks.offer(report); tasks.offer(new Task("Pay hostel fee", 3)); tasks.offer(new Task("Pack gift order", 4));
report.priority = 1;
while (!tasks.isEmpty()) { Task t = tasks.poll(); System.out.println(t.priority + " " + t.name); } }}3 Pay hostel fee 1 Submit lab report 4 Pack gift order
What this code does
- The report became the most urgent task (priority 1), but the heap had already placed it with priority 5, so the fee task still comes out first.
- Fix:
tasks.remove(report); report.priority = 1; tasks.offer(report);. Or make the priority fieldfinaland create a new object.
To find the 3 highest scores among 10 lakh, you do not need to sort everything. Keep a min-heap of size 3: offer each score, and when the size goes above 3, poll the smallest. The heap always holds the best 3 seen so far, and its top is the weakest of them. This costs O(n log k) instead of O(n log n).
The trap: the heap places an object when it is added. If you later change the field the comparator uses, the heap is not repaired and the wrong value can come out first. To change a priority, remove the object, change it, and offer it again.
Next step
Check your understanding
12 quick questions