PriorityQueue in Java
- Java PriorityQueue is a min-heap —
poll()returns the smallest element. - Use
Comparator.reverseOrder()for a max-heap; useComparator.comparing()for custom objects. - Iteration order is NOT sorted — only
poll()respects the heap ordering.
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
Basic Min-Heap Usage
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 } }
1 3 5 7 9
9 7 5 3 1
Custom Objects with Comparator
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()); } } }
[1] Deploy fix
[2] Code review
[3] Write tests
Dijkstra's Shortest Path — Classic PriorityQueue Use
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; } }
🎯 Key Takeaways
- Java PriorityQueue is a min-heap —
poll()returns the smallest element. - Use
Comparator.reverseOrder()for a max-heap; useComparator.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.
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.