Search code examples
javaqueuepriority-queue

Is iterator the best way to loop through PriorityQueue


I want to loop through a PriorityQueue, and wondering if following iterator() is the best way

Iterator<MyObject> itr = queue.iterator();
while(itr.hasNext()){
  MyObject element = itr.next();
  // do sth
}

I suppose its time complexity would be O(1)?
I don't care about the queue afterwards, so another way would be to use poll() while !queue.isEmpty() but the time complexity would be O(logn).


Solution

  • If you want ordered retrieval of your elements, you must poll/remove elements from the queue; using iterator will not be enough.