PriorityQueue for Ordered Processing
Use PriorityQueue with natural ordering and custom comparators for task scheduling scenarios.
PriorityQueue for Ordered Processing is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is a PriorityQueue?
A PriorityQueue is a min-heap by default: the element with the lowest natural ordering is always at the head. Elements are not sorted internally — only the minimum is guaranteed at the front.
import java.util.PriorityQueue;
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(30);
pq.offer(10);
pq.offer(20);
System.out.println(pq.poll()); // 10 (min)
System.out.println(pq.poll()); // 20
System.out.println(pq.poll()); // 30Internal Heap Structure
PriorityQueue uses a binary min-heap stored in an array. The parent at index i is always ≤ its children at 2i+1 and 2i+2. This guarantees O(log n) offer/poll and O(1) peek.
Max-Heap with Reversed Comparator
To create a max-heap (largest element first), pass Comparator.reverseOrder():
PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Comparator.reverseOrder());
maxPQ.offer(10);
maxPQ.offer(50);
maxPQ.offer(30);
System.out.println(maxPQ.poll()); // 50 (max)
System.out.println(maxPQ.poll()); // 30PriorityQueue with Custom Objects
Use a comparator to order custom records or classes:
record Job(String name, int priority) {}
PriorityQueue<Job> queue = new PriorityQueue<>(
Comparator.comparingInt(Job::priority) // ascending priority
);
queue.offer(new Job("Backup", 5));
queue.offer(new Job("Alert", 1));
queue.offer(new Job("Report", 3));
System.out.println(queue.poll().name()); // Alert (priority 1)Peek vs Poll
peek() returns the head element without removing it. poll() removes and returns it. Both return null on an empty queue (unlike element()/remove() which throw).
PriorityQueue<String> pq = new PriorityQueue<>();
pq.offer("banana");
pq.offer("apple");
System.out.println(pq.peek()); // apple (not removed)
System.out.println(pq.peek()); // apple (still there)
System.out.println(pq.poll()); // apple (removed)
System.out.println(pq.peek()); // bananaTask Scheduling Example
PriorityQueue is ideal for CPU scheduling simulations where tasks have different priorities:
record Task(String name, int priority) {}
PriorityQueue<Task> scheduler = new PriorityQueue<>(
Comparator.comparingInt(Task::priority).reversed() // highest first
);
scheduler.offer(new Task("Low", 1));
scheduler.offer(new Task("Critical", 10));
scheduler.offer(new Task("Normal", 5));
while (!scheduler.isEmpty()) {
System.out.println("Processing: " + scheduler.poll().name());
}
// Critical, Normal, LowK Smallest Elements
PriorityQueue is a classic tool for finding the K smallest elements without fully sorting the array:
int[] nums = {7, 2, 5, 1, 9, 3, 8};
int k = 3;
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int n : nums) pq.offer(n);
for (int i = 0; i < k; i++) {
System.out.print(pq.poll() + " ");
}
// 1 2 3K Largest Elements with Max-Heap
Alternatively, maintain a min-heap of size K while iterating to find K largest:
int[] nums = {7, 2, 5, 1, 9, 3, 8};
int k = 3;
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int n : nums) {
minHeap.offer(n);
if (minHeap.size() > k) minHeap.poll(); // remove smallest
}
// minHeap now contains the 3 largest: [7, 8, 9]
System.out.println(minHeap); // order may varyDijkstra's Algorithm Pattern
Dijkstra's shortest path algorithm relies on a min-heap to always expand the cheapest unvisited node first:
record Entry(int node, int cost) {}
PriorityQueue<Entry> pq = new PriorityQueue<>(
Comparator.comparingInt(Entry::cost)
);
pq.offer(new Entry(0, 0)); // start node, cost 0
while (!pq.isEmpty()) {
Entry curr = pq.poll();
System.out.println("Visit node " + curr.node() + " cost=" + curr.cost());
// expand neighbors...
}Iteration is Unordered
Iterating over a PriorityQueue does NOT return elements in priority order — only poll() does. For sorted output, repeatedly poll instead of using for-each.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.addAll(List.of(5,3,1,4,2));
// WRONG for sorted output:
for (int n : pq) System.out.print(n+" "); // unordered!
// CORRECT:
while (!pq.isEmpty()) System.out.print(pq.poll()+" "); // 1 2 3 4 5Performance Summary
PriorityQueue operation complexity:
- offer(e): O(log n)
- poll(): O(log n)
- peek(): O(1)
- contains(e): O(n)
- remove(e): O(n)
Not thread-safe — use PriorityBlockingQueue for concurrent access.
Quick Check
What does iterating a PriorityQueue with a for-each loop guarantee about element order?
Recap: PriorityQueue
Key takeaways:
- PriorityQueue is a min-heap: smallest element polled first
- Use Comparator.reverseOrder() for a max-heap
- O(log n) offer/poll, O(1) peek
- Classic use cases: K-th largest/smallest, Dijkstra, task scheduling
- for-each does not give priority order — use poll()
Frequently asked questions
Is the “PriorityQueue for Ordered Processing” lesson free?
Yes — the full text of “PriorityQueue for Ordered Processing” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “PriorityQueue for Ordered Processing”?
Use PriorityQueue with natural ordering and custom comparators for task scheduling scenarios. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “PriorityQueue for Ordered Processing” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- LinkedList Internals
- Deque Operations: Stack and Queue
- LinkedList vs ArrayList Trade-offs
- PriorityQueue for Ordered Processing