Say I have a queue, and I want to exhaust it. The way I would do it is something like
void emptyQueue(Queue<T> q) {
T i;
while ((i = q.poll()) != null)
consume(i);
}
but this feels like an archaic method.
I would like something more like the forEach
method. It is, of course, present - the Queue
being a Collection
- but it iterates over the elements, rather than consuming them.
Ideally, I would have liked a pollEach
method on Queue
- but I can't seem to find anything appropriate.
How do you write this kind of code?
The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null. The element() and peek() methods return, but do not remove, the head of the queue.
PriorityQueue clear() Method in Java clear() method is used to remove all the elements from a PriorityQueue. Using the clear() method only clears all the element from the queue and does not delete the queue. In other words, we can say that the clear() method is used to only empty an existing PriorityQueue.
The Queue interface is present in java. util package and extends the Collection interface is used to hold the elements about to be processed in FIFO(First In First Out) order.
You can use your own generator that calls poll()
on the queue:
Stream.generate( () -> q.poll() )
.takeWhile(Objects::nonNull) //Note that this is only available in java 9
.forEach(i -> consume(i));
This method is also an example of taking control of what passes the stream. You can manage things like blocking, etc. The takeWhile
step in this case just shows how the end of the data can be detected.
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