Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to use a queue and a stack

Short answer

ArrayDeque works both as a queue (first in, first out) and as a stack (last in, first out):

void main() {
    Deque<String> queue = new ArrayDeque<>();
    queue.offer("Anna");
    queue.offer("Oleg");
    IO.println(queue.poll());
 
    Deque<String> stack = new ArrayDeque<>();
    stack.push("page1");
    stack.push("page2");
    IO.println(stack.pop());
}

Output:

Anna
page2

Looking without removing

peek() returns the next element but leaves it in place. On an empty queue peek() and poll() return null:

void main() {
    Deque<Integer> queue = new ArrayDeque<>(List.of(1, 2));
 
    IO.println(queue.peek());
    IO.println(queue.size());
 
    queue.clear();
    IO.println(queue.poll());
}

Output:

1
2
null

A priority queue

PriorityQueue always gives you the smallest element — or the most important one according to your comparator:

record Task(String title, int priority) {}
 
void main() {
    var tasks = new PriorityQueue<>(Comparator.comparingInt(Task::priority));
    tasks.add(new Task("write tests", 2));
    tasks.add(new Task("fix bug", 1));
    tasks.add(new Task("refactor", 3));
 
    while (!tasks.isEmpty()) {
        IO.println(tasks.poll().title());
    }
}

Output:

fix bug
write tests
refactor

Common mistake

Calling pop() or remove() on an empty queue. Unlike poll(), they throw an exception:

void main() {
    Deque<String> stack = new ArrayDeque<>();
    stack.pop();
}

Output:

Exception in thread "main" java.util.NoSuchElementException

The old Stack class is synchronized and slower — use ArrayDeque in new code.

Functions used in this recipe

  • ArrayDeque — A fast array-based double-ended queue — a replacement for `Stack` and `LinkedList`.
  • Deque.push() — Pushes an element onto the top of a stack (the head of a deque).
  • Queue.poll() — Takes and removes the head of a queue.
  • PriorityQueue — A queue that always hands out the smallest (or highest-priority) element.

Thanks for reading!

Donate to the site — we work hard for you.