How to iterate over a PriorityQueue?

后端 未结 9 2055
被撕碎了的回忆
被撕碎了的回忆 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:39

    Recently, I had same problem. I wanted to use some particular object from the priority queue and then keep remaining elements preserved.

    1) I created a newPriorityQueue. 2) Used Iterator to parse every element in oldQueue 3) used oldQueue.poll() method to retrieve the element 4) insert the element 3) to newPriorityQueue if not used.

     Queue newQueue = new PriorityQueue(); 
        // Assuming that oldQueue have some data in it.
    
        Iterator itr = oldQueue.iterator();
        while(itr.hasNext()){
            String str = oldQueue.poll();
            // do some processing with str
            if(strNotUsed){
                newQueue.offer(str);
            }
        }
    

    In the end, oldQueue will be empty. @ Others : - please suggest a better way if I can do the same thing. I can not use the iterator as it does not return elements in the correct order.

提交回复
热议问题