Queue, Deque and PriorityQueue

Collections · lesson 9 of 42 · 3 min read

Model stacks, queues and priority ordering with the right JDK type.

Open this lesson in the learning hub

Key points

  • ArrayDeque is the modern answer for both stacks and queues. Use it instead of the legacy Stack class.
  • Stack: push, pop, peek. Queue: offer, poll, peek.
  • poll and peek return null when empty. remove and element throw instead.
  • PriorityQueue always hands you the smallest element by natural order or by your Comparator.
  • A PriorityQueue is a heap, so its toString and its iterator are not in sorted order. Only poll is ordered.
  • ArrayDeque does not accept null elements — null is its "empty" signal.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Deque<String> stack = new ArrayDeque<>();
        stack.push("a"); stack.push("b"); stack.push("c");
        System.out.println("stack  pop order : " + stack.pop() + stack.pop() + stack.pop());

        Queue<String> queue = new ArrayDeque<>();
        queue.offer("a"); queue.offer("b"); queue.offer("c");
        System.out.println("queue poll order : " + queue.poll() + queue.poll() + queue.poll());
        System.out.println("poll when empty  : " + queue.poll());

        Deque<Integer> both = new ArrayDeque<>();
        both.addFirst(2); both.addFirst(1); both.addLast(3);
        System.out.println("deque            : " + both);
        System.out.println("peekFirst/Last   : " + both.peekFirst() + " / " + both.peekLast());

        PriorityQueue<String> pq = new PriorityQueue<>(Comparator.comparingInt(String::length));
        pq.addAll(List.of("banana", "fig", "kiwi", "plum"));
        System.out.println("heap toString    : " + pq + "   (NOT sorted)");
        StringBuilder drained = new StringBuilder();
        while (!pq.isEmpty()) drained.append(pq.poll()).append(' ');
        System.out.println("drained shortest : " + drained.toString().trim());
    }
}

ArrayDeque for both ends, PriorityQueue when order of removal matters more than order of arrival.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.