How to iterate over a PriorityQueue?

simpatico picture simpatico · Nov 14, 2011 · Viewed 59.9k times · Source
for (Event e : pq)

doesn't iterate in the priority order.

while(!pq.isEmpty()){
  Event e = pq.poll();
}

This works but empties the queue.

Answer

Oliver Charlesworth picture Oliver Charlesworth · Nov 14, 2011

From the Javadocs

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

There are probably other equivalent mechanisms.