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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With