Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate PriorityBlockingQueue in order

Tags:

java

I have a PriorityBlockingQueue<Shirts> that uses a FIFO (first in first out) comparator in addition to other custom conditions. While obeying the priority, I need to pull out only the Green shirts. I understand the objective with a Queue is that they are intended for items to be "taken off of the top". The iterator() doesn't obey the order, so I can't use that. Should I be using a different queue altogether? How can I iterate over these items.

like image 358
Webnet Avatar asked Sep 06 '13 14:09

Webnet


1 Answers

PriorityQueue.iterator() doesn't obey the order but retrieval operations poll, remove, peek, and element access the element at the head of the queue. So, taking into consideration that PriorityBlockingQueue cannot have null elements, you can iterate the elements in order this way

PriorityBlockingQueue<Shirts> q = ...
for (Shirts shirts; (shirts = q.poll()) != null; ) {
    ...      
}

Another way

     Shirts[] a = q.toArray(new Shirts[q.size()]);
     Arrays.sort(a);

now you can iterate in both direction

like image 117
Evgeniy Dorofeev Avatar answered Oct 16 '22 13:10

Evgeniy Dorofeev