Java PriorityQueue
In this page:
PriorityQueue<Type> queue = new PriorityQueue<>();
queue.offer(item);
queue.poll(); // smallest first
queue.peek();
Introduction to PriorityQueue
A PriorityQueue is a queue implementation where elements are dequeued based on priority rather than plain first-in-first-out order. By default it behaves as a min-heap, always placing the smallest element (by natural ordering) at the head, ready to be polled first.
Example: Introduction to PriorityQueue
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5); pq.add(1); pq.add(3);
System.out.println(pq.poll()); // smallest first: 1
}
}
Login to try C/C++/Java/PHP code in the editor
Creating a Max-Heap Queue
You can flip a PriorityQueue into a max-heap, where the largest element sits at the head instead of the smallest, by passing Collections.reverseOrder(), or an equivalent custom reverse comparator, into its constructor.
Example: Creating a Max-Heap Queue
import java.util.PriorityQueue;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.add(5); maxHeap.add(1); maxHeap.add(3);
System.out.println(maxHeap.poll()); // largest first: 5
}
}
Login to try C/C++/Java/PHP code in the editor
Custom Objects in PriorityQueue
You can store custom objects inside a PriorityQueue as long as the class implements Comparable, defining its natural order, or you pass a custom Comparator into the queue's constructor telling it how to rank those objects instead.
Example: Custom Objects in PriorityQueue
// Import java.util.PriorityQueue so it can be used by its short name
import java.util.PriorityQueue;
// Import java.util.Comparator so it can be used by its short name
import java.util.Comparator;
// Define the class Main
public class Main {
// Define the record Task (an immutable data carrier)
record Task(String name, int priority) {}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a new PriorityQueue object and store it in pq
PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority));
pq.add(new Task("Low", 3));
pq.add(new Task("High", 1));
// Print a line to the console
System.out.println(pq.poll());
}
}
Login to try C/C++/Java/PHP code in the editor
Queue Maintenance and Traversal
You can check a PriorityQueue's current size, test whether it's empty, or search for and remove a specific element from anywhere inside it, though removal of an arbitrary (non-head) element is a linear-time operation since the internal heap array isn't fully sorted.
Example: Queue Maintenance and Traversal
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5); pq.add(1); pq.add(3);
System.out.println(pq.size() + " " + pq.isEmpty());
pq.remove(3); // linear-time, not the head
System.out.println(pq);
}
}
Login to try C/C++/Java/PHP code in the editor
Dynamic Sorting Simulator
A PriorityQueue is especially useful for managing datasets that update dynamically over time, such as a task scheduler or a running top-K tracker, since it always keeps the highest (or lowest) priority element instantly accessible without needing to re-sort the whole collection.
Example: Dynamic Sorting Simulator
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> topScores = new PriorityQueue<>();
int[] incoming = {50, 90, 20, 70};
for (int score : incoming) {
topScores.add(score);
if (topScores.size() > 2) topScores.poll(); // keep top 2
}
System.out.println(topScores);
}
}
Login to try C/C++/Java/PHP code in the editor
- Printing or iterating a
PriorityQueueand expecting sorted output, when only the head is guaranteed to be the smallest and the rest is in heap order. - Expecting a max-heap by default, when it is a min-heap; pass
Collections.reverseOrder()to get the largest first. - Adding objects that are not
Comparablewithout a Comparator, which throws aClassCastException.
TreeMap,TreeSet, andLinkedHashMapoffer sorted or insertion-ordered collections.ComparableandComparatordefine how objects are compared and sorted.PriorityQueueprocesses elements by priority.
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: