Queue, Deque and PriorityQueue
Model stacks, queues and priority ordering with the right JDK type.
Open this lesson in the learning hubKey points
ArrayDequeis the modern answer for both stacks and queues. Use it instead of the legacyStackclass.- Stack:
push,pop,peek. Queue:offer,poll,peek. pollandpeekreturnnullwhen empty.removeandelementthrow instead.PriorityQueuealways hands you the smallest element by natural order or by yourComparator.- A PriorityQueue is a heap, so its
toStringand its iterator are not in sorted order. Onlypollis ordered. ArrayDequedoes not acceptnullelements —nullis 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.