Intermediate · The collections framework · topic 35 of 60 · 25 min
Queues, stacks and priority queues
Explanation
Queue: first in, first out
A queue serves items in arrival order, like a token system at a clinic. In Java, Queue is an interface; ArrayDeque is the usual implementation. offer adds at the tail, poll removes from the head (null when empty), and peek looks at the head without removing it.
Queue<String> tokens = new ArrayDeque<>();
tokens.offer("T1");
tokens.offer("T2");
tokens.offer("T3");
System.out.println(tokens.peek()); // T1 (still there)
System.out.println(tokens.poll()); // T1 (removed)
System.out.println(tokens); // [T2, T3]Queue also has add, remove and element, which THROW an exception when they fail (for example remove on an empty queue), while offer, poll and peek return false or null instead.
Stack with ArrayDeque
Deque<String> undo = new ArrayDeque<>();
undo.push("typed 'Hello'");
undo.push("made bold");
undo.push("deleted line");
System.out.println(undo.pop()); // deleted line (last in, first out)
System.out.println(undo.peek()); // made boldThe old java.util.Stack class extends Vector, is synchronised (slower) and is considered legacy. The Javadoc itself recommends Deque/ArrayDeque for stacks.
PriorityQueue: most important first
PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(40, 10, 30, 20));
System.out.println(pq.poll()); // 10 (smallest first: a min-heap)
System.out.println(pq.poll()); // 20
record Patient(String name, int severity) {} // 1 = most critical
PriorityQueue<Patient> er = new PriorityQueue<>(Comparator.comparingInt(Patient::severity));
er.offer(new Patient("Asha", 3));
er.offer(new Patient("Ravi", 1));
er.offer(new Patient("Om", 2));
System.out.println(er.poll().name()); // Ravi (most critical)Utility methods and choosing a collection
Collections offers helpers: Collections.max, min, frequency, reverse, shuffle, unmodifiableList and nCopies. To choose a collection, ask how you will USE it.
| Need | Use |
|---|---|
| Ordered list, access by index | ArrayList |
| Unique items, fast contains | HashSet (LinkedHashSet for order, TreeSet for sorted) |
| Lookup by key | HashMap (LinkedHashMap / TreeMap for order) |
| FIFO queue or LIFO stack | ArrayDeque |
| Always take the smallest / highest priority | PriorityQueue |
| Many threads at once | ConcurrentHashMap, BlockingQueue (module 9) |
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Queues, stacks and priority queues · 1/6
In this lesson you will use queues, stacks and priority queues.
Prefer a video by a teacher? Find free videos on “java queue deque arraydeque priorityqueue stack tutorial” on YouTube ↗
In real life: Hospital emergency triage
An emergency department's system queues patients by severity (1 = critical, 5 = minor) using a PriorityQueue, with arrival time as a tie-break so equally severe patients are seen in order.
record Arrival(String name, int severity, int arrivedMin) {}
PriorityQueue<Arrival> triage = new PriorityQueue<>(
Comparator.comparingInt(Arrival::severity).thenComparingInt(Arrival::arrivedMin));
triage.offer(new Arrival("Asha", 3, 5));
triage.offer(new Arrival("Ravi", 1, 9));
triage.offer(new Arrival("Om", 3, 2));
while (!triage.isEmpty()) System.out.println(triage.poll().name()); // Ravi, Om, AshaPractice (0/3 done)
What does this print? Deque<Integer> d = new ArrayDeque<>(); d.push(1); d.push(2); d.offer(3); System.out.println(d.pop() + " " + d.pollLast());
The same stack algorithm in JavaScript, which runs here: write isBalanced(s) that returns true when every (, [ and { is closed in the right order, using an array as a stack.
Simulate a clinic: patients arrive as records Patient(name, severity, arrival). Use a PriorityQueue with a comparator (severity, then arrival) and print the order in which they are seen. Then use an ArrayDeque as a simple FIFO queue for the pharmacy counter and print its order.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Maps: HashMap, LinkedHashMap and TreeMapThe collections framework · same module
- Sets: HashSet, LinkedHashSet and TreeSetThe collections framework · same module
- Stacks and queuesPython Programming · Algorithms, data structures and testing
- set, stack, queue, deque and priority_queueC++ Programming (modern C++ and DSA) · The Standard Template Library (STL)
- Heaps and priority queuesData Structures and Algorithms (DSA) for interviews · Heaps and greedy algorithms
- Queues and dequesData Structures and Algorithms (DSA) for interviews · Stacks, queues and linked lists
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which removes and returns the head of a Queue, or null if it is empty?
Answer: poll()
poll returns null when empty; remove throws.
A PriorityQueue<Integer> created with no comparator gives…
Answer: The smallest first
The default is a min-heap by natural order.
Which class should implement a stack in modern Java?
Answer: ArrayDeque
ArrayDeque is recommended over Stack.
Which order does a stack follow?
Answer: LIFO
Last in, first out.
Which is the best tool for a large FIFO queue in Python?Related
Answer: collections.deque with append and popleft
deque adds and removes at both ends in O(1). list.pop(0) shifts every item, which is O(n).
From Stacks and queues
std::priority_queue<int> pq; after pushing 4, 9 and 2, what is pq.top()?Related
Why push (priority, counter, item) instead of (priority, item)?Related
Answer: Equal priorities then compare the counter, so items are never compared and arrival order is kept
Without the counter, a tie compares the items, which may raise TypeError or give an unwanted order.
A circular queue has capacity 4, head = 3 and count = 2. Which slot does the next enqueue use?Related
Answer: 1
(3 + 2) % 4 = 1. The items sit in slots 3 and 0; the next one goes in slot 1.
From Queues and deques
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “The collections framework”. The module exam comes next.
- Module 7 exam: The collections framework · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Lambdas, streams and files. 60 topics left in the course before the final exam.