How to iterate over a PriorityQueue?

后端 未结 9 2069
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 03:48
for (Event e : pq)

doesn\'t iterate in the priority order.

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

This wo

9条回答
  •  暖寄归人
    2020-11-30 04:17

    A heap based priority queue only guarantees that the first element is the highest/lowest. There is no cheap (i.e. O(n)) way to get the elements in sorted form.

    If you need to do this often, consider using a structure that maintains the elements in sorted form. For example, use java.util.TreeSet, and use either pollFirst() or pollLast() in place of peek() / poll()

提交回复
热议问题