Queue and Deque

Basic Java
≈ 2 min read

Queue: processing in line

Queue<E> describes a structure from which elements are usually taken in their processing order. For a regular queue, this is FIFO: first in, first out — the first element to arrive is the first one to leave.

Queue<String> tasks = new ArrayDeque<>();
tasks.offer("build");
tasks.offer("test");
tasks.offer("deploy");

System.out.println(tasks.poll()); // build
System.out.println(tasks.peek()); // test

offer() adds an element, poll() takes and removes the next one, and peek() only looks at it. If the queue is empty, poll() and peek() return null.

Two groups of methods

A queue has similar operations with different behavior when an action cannot be performed. add(), remove(), and element() report a problem with an exception, while offer(), poll(), and peek() use a special result. For ordinary queue processing in application code, the second group is often more convenient.

Deque: access from both ends

Deque<E> extends the queue idea: elements can be added and removed from both the beginning and the end. That means the same structure can act as either a queue or a stack.

Deque<String> history = new ArrayDeque<>();
history.addLast("page-1");
history.addLast("page-2");
history.addFirst("start");

System.out.println(history.removeFirst()); // start
System.out.println(history.removeLast());  // page-2

The First and Last names make the side of the operation explicit, so code using Deque is usually easy to read.

For a regular stack, prefer Deque to the old Stack class. For example, ArrayDeque provides the modern operations push(), pop(), and peek().