How should I iterate a priority queue properly?
Solution 1
Yes, if you need to check every single element in the collection, an iterator
or for each
is probably best.
Iterator<E> iter = myPriorityQueue.iterator();
while (iter.hasNext()) {
current = iter.next();
// do something with current
}
Or
for (Element e : myQueue) {
// do something with e
}
Solution 2
One small detail: if there's any chance your queue could be modified during the loop, then both iterator
and for each
will cause a ConcurrentModificationException
; if there's a chance the queue will get modified during the processing, you could use poll()
:
Resource resource;
while ((resource = resourceQueue.poll()) != null) {
this.processIncludes(resourceQueue, resource);
}
Solution 3
If you don't care about ordering (in that case - why are you dealing with PriorityQueue
?), use Iterator. If you want to iterate by priority, then see the advice from Javadoc:
If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
Anon
Updated on June 02, 2020Comments
-
Anon almost 4 years
I have a java assignment involving iterating a priority queue. The queue consists of objects with a string and an int in them and i need to have a way to check a seperate object's string against all the objects in the queue.
Would it be best way to do this be an iterator object? That seems too messy. I could dequeue and enqueue but that seems inefficient. Maybe a foreach loop?
-
Thomas Jungblut over 11 yearsExactly, it is based on a heap which does prohibit complete ordering in itself. Thus you should call poll, because this will cause the heap to sift the min/max up to the root. But for his requirement, ordering doesn't matter, so he could iterate by a for each loop.
-
Anon over 11 yearsIm told I have to use a priority queue. It doesnt matter though what order I traverse it. I just need to check each objects string to make sure it doesnt match my seperate object's string