Course contentsShow
← Java
Lesson 1190 of 2,87027. Queue and Deque ImplementationsFree lesson

Iteration Order Is Not Priority Order

Understand that iterating a PriorityQueue does not yield elements in priority order; only poll guarantees order.

Iteration Order Is Not Priority Order

You'll learn: Why looping through a PriorityQueue doesn't give you elements in sorted order.

The Surprising Truth About PriorityQueue Iteration

Here's something that trips up almost every beginner: when you iterate over a PriorityQueue using a for-each loop or an iterator, the elements do not appear in priority order. This seems contradictory—isn't it a priority queue?

The confusion comes from misunderstanding what a PriorityQueue guarantees. It only promises that the highest-priority element is at the head (accessible via peek() or poll()). The internal arrangement—the binary heap—doesn't maintain full sorted order throughout the entire structure.

Why This Happens

Remember that a PriorityQueue uses a binary heap under the hood. The heap ensures the smallest (or largest, depending on your comparator) element is at position zero, but siblings and cousins in the tree aren't necessarily in order relative to each other. When you iterate, you're traversing the underlying array representation of the heap, which exposes this partial ordering.

The Correct Way to Get Priority Order

If you need elements in priority order, repeatedly call poll():

PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(1);
pq.offer(3);

// Wrong: iteration order is unpredictable
for (Integer num : pq) {
    System.out.println(num); // Might print: 1, 5, 3
}

// Correct: poll until empty
while (!pq.isEmpty()) {
    System.out.println(pq.poll()); // Always prints: 1, 3, 5
}

Key Takeaway: Iterating a PriorityQueue shows elements in heap order (unpredictable), not priority order. Only poll() guarantees you get elements by priority.