what's the best way to poll a queue in a loop? I s...
# announcements
t
what's the best way to poll a queue in a loop? I suppose a normal for-loop wouldn't remove the elements from the queue
a
blocking or non-blocking?
t
non-blocking. The loop should terminate after the queue is empty
a
then I'd go with a simple
while(true) { val item = queue.poll(); if(item == null) break ... }
t
That's what I ended up with but it doesn't look idiomatic
a
@tschuchort you can write your own iterator:
Copy code
class QueueIterator<T>(private val queue: Queue<T>) : Iterator<T> {
    override fun hasNext() = queue.peek() != null

    override fun next() = queue.poll()
}

fun Queue<T>.pollIterator() = QueueInterator(this)
and then use it like this
for(item in queue.pollIterator()) { ... }
👍 1