Java Notes
Learn Java PriorityQueue — min-heap by default, processing elements by priority instead of arrival order, custom Comparator for max-heap, and practical use cases.
PriorityQueue does not process elements in arrival order like a regular queue. Instead, it always processes the element with the highest priority first. By default, the smallest element has the highest priority (min-heap). You can reverse this or define any custom priority with a Comparator.
Basic Usage — Min-Heap (default)
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
- Adding elements in any order — 40, 10, 30, 20.
pq.poll()— always returns the smallest: 10, then 20, then 30, then 40.pq.peek()— look at the smallest without removing.- Printing
pqdirectly does NOT show sorted order — it shows the internal heap array.
Max-Heap — Custom Comparator
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Real Use Case: Task Scheduling by Priority
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Tasks with priority 1 are processed first. Among tasks with the same priority, order is not guaranteed (heap is not a sort).
PriorityQueue With Strings (Natural Order = Alphabetical)
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
For Strings, "natural order" is alphabetical — poll() always gives the alphabetically smallest remaining string.
Common Mistake: Assuming Poll Returns Insertion Order
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(3);
pq.offer(1);
pq.offer(2);
System.out.println(pq.poll()); // 1 — NOT 3 (not FIFO!)PriorityQueue is NOT a FIFO queue. It always returns the smallest (or highest priority) element, regardless of insertion order.
Practice Task
Task: Use PriorityQueue<Integer> to find the 3 smallest numbers from the array {42, 7, 18, 3, 99, 55, 12, 1} without sorting the full array.
Hint: Add all elements to a PriorityQueue (min-heap). Call poll() three times — each call gives the next smallest.
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: First poll() gives 1, second gives 3, third gives 7 — the three smallest in order. The rest of the array is untouched. For the 3 largest instead, use Collections.reverseOrder() as the comparator.
Continue the lesson path