The PriorityQueue
in Java is a powerful tool for managing elements based on priority rather than insertion order — super useful in many real-world scenarios like scheduling, simulations, and pathfinding algorithms (like Dijkstra!).
🎯 What PriorityQueue
Can Do
✅ Maintains elements in priority order, not insertion order.
- By default, it’s a min-heap — the smallest element is always at the head.
- You can provide a custom comparator to change the order (e.g., max-heap).
✅ Efficient operations:
Operation | Time Complexity | Description |
---|---|---|
add(e) / offer(e) | O(log n) | Insert new element, auto-reorders heap |
poll() | O(log n) | Removes and returns highest priority |
peek() | O(1) | Views head (highest priority) |
🧪 Example: Default (Min-Heap)
import java.util.PriorityQueue;
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5);
pq.add(1);
pq.add(3);
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // Output: 1, 3, 5
}
✅ Elements come out sorted, smallest first.
🔧 Example: Max-Heap (Custom Comparator)
PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a, b) -> b - a);
maxPQ.add(5);
maxPQ.add(1);
maxPQ.add(3);
while (!maxPQ.isEmpty()) {
System.out.println(maxPQ.poll()); // Output: 5, 3, 1
}
🧠 Use Cases for PriorityQueue
Use Case | Why It Fits |
---|---|
Task scheduling (OS, jobs) | Execute high-priority tasks first |
Dijkstra’s algorithm | Visit node with smallest distance |
Event-driven simulation | Process events in time order |
Real-time systems | Handle critical events sooner |
K largest/smallest elements | Keeps top-k efficiently |
⚠️ Limitations
- ❌ No random access (
get(i)
not supported). - ❌ Not thread-safe — use
PriorityBlockingQueue
if you need concurrency. - ❌ Iterating doesn’t give sorted order — you need to
poll()
.
🤖 TL;DR:
PriorityQueue
is a heap-based structure for managing elements by priority, not position. It’s great for efficient priority-based processing in O(log n) time.