Should a Priority Queue Be Iterable?

Since the iterator chapter, every collection we have added has been iterable. A priority queue could be too. Its elements are stored somewhere, so we could always iterate over them. The question is whether iteration belongs in this abstraction.

The set and the map are iterable because iteration is the only way to list what they hold. The stack and the queue are not. They are restricted-access structures: a stack lets you reach only its top, and a queue only its front. An iterator would give the caller access to every element, and that undoes the restriction.

A priority queue is restricted in the same way. It lets you look at and remove only the highest-priority element. So we leave it non-iterable. If you often need to traverse, search, or display all the elements, a priority queue is the wrong data structure.

This is a design decision. Java’s PriorityQueue is iterable, but its documentation says the iteration is “not guaranteed … in any particular order.” So even in Java, iterating over a priority queue does not give you the elements in priority order, and priority order is the only order that means something for this structure.