Many programs process items in a particular order: customers served in the order they arrive, browser pages revisited in reverse, hospital patients treated by urgency. Java’s collections framework has a ready-made structure for each of these. A Queue serves first in, first out. A Deque (double-ended queue) works at both ends and makes a fast stack. A PriorityQueue always hands out the most important item next. This lesson uses all three.
In this lesson you will learn
- The
Queueinterface:offer,pollandpeek - Using
ArrayDequeas a stack withpushandpop - Adding and removing at both ends of a
Deque PriorityQueueas a min-heap and a max-heap- Ordering custom objects by priority
You should know ArrayList and Comparable and Comparator.
Queue and Deque
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
// Queue: first in, first out (FIFO)
Queue<String> tickets = new ArrayDeque<>();
tickets.offer("Karim");
tickets.offer("Rina");
tickets.offer("Joya");
System.out.println("Next: " + tickets.peek() + ", queue: " + tickets);
System.out.println("Served: " + tickets.poll() + ", then " + tickets.poll());
tickets.poll();
System.out.println("Empty: " + tickets.isEmpty() + ", poll() now returns " + tickets.poll());
// Deque used as a stack: last in, first out (LIFO)
Deque<String> history = new ArrayDeque<>();
history.push("home");
history.push("courses");
history.push("java");
System.out.println("Stack: " + history + ", back to: " + history.pop() + ", now on: " + history.peek());
// Deque used at both ends
Deque<Integer> d = new ArrayDeque<>();
d.offerFirst(2); d.offerFirst(1); d.offerLast(3); d.offerLast(4);
System.out.println(d + " first=" + d.peekFirst() + " last=" + d.peekLast());
d.pollFirst(); d.pollLast();
System.out.println(d);
}
}
Output
Next: Karim, queue: [Karim, Rina, Joya]
Served: Karim, then Rina
Empty: true, poll() now returns null
Stack: [java, courses, home], back to: java, now on: courses
[1, 2, 3, 4] first=1 last=4
[2, 3]
- A
Queueis FIFO (first in, first out), like a ticket line.offeradds at the back,pollremoves from the front, andpeeklooks at the front without removing it. pollandpeekreturnnullon an empty queue. The alternative methodsremoveandelementthrow an exception instead.- A
Dequeused withpushandpopis a stack: LIFO (last in, first out), like the browser’s back button.popreturned “java”, the last page pushed. offerFirst,offerLast,pollFirstandpollLastwork at either end, so oneArrayDequecan be a queue, a stack, or both.- Prefer
ArrayDequeover the oldStackclass and, for most queues, overLinkedList. It is faster and uses less memory. It does not acceptnullelements.
PriorityQueue
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
record Patient(String name, int urgency) {}
public static void main(String[] args) {
// PriorityQueue: always removes the smallest element first
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int x : new int[] {42, 7, 19, 3, 25}) pq.offer(x);
System.out.println("peek = " + pq.peek());
StringBuilder order = new StringBuilder();
while (!pq.isEmpty()) order.append(pq.poll()).append(' ');
System.out.println("poll order: " + order.toString().trim());
// Max-heap: largest first
PriorityQueue<Integer> max = new PriorityQueue<>(Comparator.reverseOrder());
max.addAll(java.util.List.of(42, 7, 19, 3, 25));
System.out.println("largest = " + max.poll() + ", next = " + max.poll());
// Emergency room: highest urgency is treated first
PriorityQueue<Patient> er = new PriorityQueue<>(
Comparator.comparingInt(Patient::urgency).reversed());
er.offer(new Patient("Sabbir", 2));
er.offer(new Patient("Mitu", 5));
er.offer(new Patient("Imran", 1));
er.offer(new Patient("Nadia", 4));
while (!er.isEmpty()) {
Patient p = er.poll();
System.out.println("treat " + p.name() + " (urgency " + p.urgency() + ")");
}
}
}
Output
peek = 3
poll order: 3 7 19 25 42
largest = 42, next = 25
treat Mitu (urgency 5)
treat Nadia (urgency 4)
treat Sabbir (urgency 2)
treat Imran (urgency 1)
- A
PriorityQueueis a heap.pollalways removes the smallest element, so the numbers come out sorted: 3, 7, 19, 25, 42. - Printing the queue directly would not show sorted order. Only the head is guaranteed to be the smallest; the rest are arranged as a heap internally.
- Passing
Comparator.reverseOrder()makes a max-heap, which removes the largest element first. - For your own objects, give the queue a comparator. Patients are treated by urgency, highest first, whatever order they arrived in.
- Adding and removing take O(log n) time, and
peektakes O(1). That makes priority queues the standard tool for scheduling, “top K” problems and Dijkstra’s shortest-path algorithm.
Which One to Use
| Need | Use | Main methods |
|---|---|---|
| First in, first out | ArrayDeque as a Queue | offer, poll, peek |
| Last in, first out (stack) | ArrayDeque as a Deque | push, pop, peek |
| Both ends | ArrayDeque | offerFirst/Last, pollFirst/Last |
| Most important first | PriorityQueue | offer, poll, peek |
| Shared between threads | ArrayBlockingQueue, LinkedBlockingQueue | put, take |
Common Mistakes
- Expecting a printed
PriorityQueueto be sorted. Poll the elements one by one to get sorted order. - Using
remove()on an empty queue, which throwsNoSuchElementException. Usepoll()and check fornull. - Using
java.util.Stack, an old synchronised class. UseArrayDeque. - Changing an object’s priority while it is inside a
PriorityQueue. The heap does not notice; remove it, change it, and add it again.
Practice Exercises
Exercise 1. Use a stack to check whether the brackets in "{[()()]}" are balanced.
Show answer
static boolean balanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if ("([{".indexOf(c) >= 0) stack.push(c);
else {
if (stack.isEmpty()) return false;
char open = stack.pop();
if ("([{".indexOf(open) != ")]}".indexOf(c)) return false;
}
}
return stack.isEmpty();
}
// balanced("{[()()]}") is true, balanced("([)]") is false
Exercise 2. Find the 3 largest numbers in a list using a min-heap of size 3.
Show answer
PriorityQueue<Integer> top = new PriorityQueue<>();
for (int x : List.of(42, 7, 19, 3, 25, 31)) {
top.offer(x);
if (top.size() > 3) top.poll(); // drop the smallest
}
System.out.println(top); // contains 25, 31 and 42 (heap order)
Keeping only k items makes this O(n log k), faster than sorting everything when k is small.
Frequently Asked Questions
Is LinkedList a Queue?
Yes. LinkedList implements both List and Deque, so it can be used as a queue. It also allows null elements. ArrayDeque is usually faster.
Is PriorityQueue thread-safe?
No. For several threads, use PriorityBlockingQueue from java.util.concurrent; see Java multithreading.
Summary
- Queues are FIFO:
offerat the back,pollfrom the front. ArrayDequeis the go-to queue and stack.PriorityQueuealways returns the smallest (or highest-priority) element.- Give a comparator to change the priority order.
Next: Java Optional.
