Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to exhaust a Queue in Java 8?

Tags:

java

java-8

queue

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?

like image 835
Bex Avatar asked Jun 04 '18 07:06

Bex


People also ask

What is the difference between poll () and remove () method of Queue?

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.

How do you clear a Queue in Java?

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.

What is Java Queue interface?

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.


1 Answers

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.

like image 76
ernest_k Avatar answered Oct 29 '22 17:10

ernest_k