Queue.poll()
Takes and removes the head of a queue.
Available since: Java 1.5
Syntax
E poll()Return value
EThe head element removed from the queue, or `null` if the queue is empty.
Examples
Processing a queue to the end:
void main() {
Queue<String> tasks = new ArrayDeque<>(List.of("build", "test", "deploy"));
String task;
while ((task = tasks.poll()) != null) {
IO.println("Run " + task);
}
IO.println(tasks.poll());
}Output:
Run build
Run test
Run deploy
nullNotes
On an empty queue poll() returns null, while remove() throws NoSuchElementException. Deque has pollFirst() and pollLast() for both ends.
See also
- Queue.offer() — Adds an element to the tail of a queue.
- Queue.peek() — Returns the head of a queue without removing it.
- Deque.pop() — Removes and returns the element at the top of a stack.
Related recipes
In the tutorial
- Queues and deques — Queues in Java: Queue and ArrayDeque, a stack built on Deque, the offer, poll and peek methods and the PriorityQueue.