Lists and maps do not express every processing policy. A queue expresses an order of work. ArrayDeque can provide first-in-first-out behavior; PriorityQueue selects the next item using a comparator. Understanding removal order matters more than the collection's printed appearance.
Understand the contract
A deque is a double-ended queue. With addLast and removeFirst, items leave in arrival order. ArrayDeque rejects null entries. removeFirst throws on empty input, so the example checks isEmpty. pollFirst is an alternative returning null for empty; choose the behavior your caller can handle.
A PriorityQueue instead exposes the smallest item according to its comparator through poll or remove. It does not keep its iteration order globally sorted. To produce priority order, repeatedly remove the head from a working queue; do not rely on printing the queue or traversing it with a for loop.
These queues are local, single-threaded containers. They are not worker pools or thread-safe messaging systems. An ordering policy can be learned here without threads. If several callers later share a queue concurrently, the ownership and synchronization problem is additional and requires a real JVM exercise.
Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque<String> work = new ArrayDeque<>();
work.addLast("Read");
work.addLast("Test");
while (!work.isEmpty()) {
System.out.println(work.removeFirst());
}
System.out.println(work.size());
}
}Check your prediction
Read
Test
0Trace a different case
Ties need an explicit policy. The Job comparator orders by duration and then ID, so two equal-duration jobs have predictable output independent of arrival order. PriorityQueue<>(comparator) configures the ordering. queue.addAll(source) appends every source item to the queue; it does not empty or edit the source. Poll removes and returns the head; calling it consumes that queue, so copy data into a separate queue if the source must remain available.
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
Comparator<Job> order = Comparator.comparingInt(Job::minutes).thenComparing(Job::id);
PriorityQueue<Job> work = new PriorityQueue<>(order);
work.add(new Job("B", 10));
work.add(new Job("A", 10));
work.add(new Job("C", 5));
while (!work.isEmpty()) {
System.out.println(work.remove().id());
}
}
}
record Job(String id, int minutes) {}Check your prediction
C
A
BSeparate selection order from storage appearance
FIFO answers “which item arrived first?” A priority queue answers “which item should be selected next under this comparator?” Neither means its printed internal arrangement is a complete sorted report. Head removal is the operation whose order the priority queue promises.
Trace B/10, A/10 and C/5 using the duration-and-ID policy. C leaves first because of duration, then A before B because of the tie-breaker. A test without a tie cannot protect that secondary rule. A test without unequal priorities cannot protect the primary rule.
Removing work changes the queue. Copy input into a working queue when a caller still needs the source. For a complete one-off report, sorting a copy may be simpler; for arriving work, repeated head selection expresses a different workload.
Debug a plausible mistake
The comparator's direction choices are independent. Reversing a complete chain reverses its ID ties as well as its primary duration order. A queue would obey the same comparator policy; a sorted copy keeps this diagnostic focused on that policy.
Repair the tie direction
Order jobs by descending minutes and then ascending ID. The report must print A, B, C. Preserve the source. Reverse the source order afterward and confirm the same report order. Predict what the current program actually prints before changing it. Make the smallest justified repair. The supplied version compiles; its behavior is the problem.
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
List<Job> source = List.of(new Job("B", 10), new Job("A", 10), new Job("C", 5));
List<Job> report = new ArrayList<>(source);
Comparator<Job> byMinutes = Comparator.comparingInt(Job::minutes);
report.sort(byMinutes.thenComparing(Job::id).reversed());
for (Job job : report) {
System.out.println(job.id());
}
}
}
record Job(String id, int minutes) {}Hint 1: the idea
The primary order should reverse while the secondary order should stay ascending.
Hint 2: a first step
Reverse byMinutes before attaching the ID extractor.
Show one solution
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
List<Job> source = List.of(new Job("B", 10), new Job("A", 10), new Job("C", 5));
List<Job> report = new ArrayList<>(source);
Comparator<Job> byMinutes = Comparator.comparingInt(Job::minutes);
report.sort(byMinutes.reversed().thenComparing(Job::id));
for (Job job : report) {
System.out.println(job.id());
}
}
}
record Job(String id, int minutes) {}Expected output after repair:
A
B
C.reversed() applies to the whole comparator it is called on. In the original,
that was minutes-then-ID, so both parts flipped: the ties came out B before A,
and the output was B, A, C. Calling byMinutes.reversed() first flips only the
duration, then thenComparing(Job::id) adds an ascending tie-breaker. Reversing
the source list cannot change the result, because every pair of jobs now has a
defined order.
Build it yourself
Queues & Work Order: practice
A priority queue earns its place when work keeps arriving. Simulate a worker
that, at every tick 0, 1, 2…, first adds the jobs that arrive at that tick, then
runs one waiting job: the shortest, with ID as the tie-breaker. If nothing is
waiting it does nothing that tick. Write run(List<Arrival>) returning a log of
tick:ID entries. Arrivals are given in tick order; stop when every job has
arrived and run. A job runs in one tick whatever its minutes: minutes only
decide which waiting job goes first, not how long it takes.
Predict the log before you code it. With the arrivals in the workspace, the
answer is [0:A, 1:C, 2:B, 3:D, 5:E], and empty input gives []. Note that
D, the shortest job of all, does not run first: it has not arrived yet.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
List<Arrival> arrivals = List.of(
new Arrival(0, new Job("A", 10)),
new Arrival(0, new Job("B", 10)),
new Arrival(1, new Job("C", 2)),
new Arrival(3, new Job("D", 1)),
new Arrival(5, new Job("E", 5)));
System.out.println(run(arrivals));
System.out.println(run(List.of()));
}
static List<String> run(List<Arrival> arrivals) {
// At each tick: add the jobs arriving now, then remove one waiting job.
return List.of();
}
}
record Job(String id, int minutes) {}
record Arrival(int tick, Job job) {}Hint 1: the idea
Sorting all five jobs up front would give D, C, E, A, B, which runs jobs before they exist. The queue must hold only what has arrived so far, so the loop alternates: admit arrivals for this tick, then remove one head.
Hint 2: a first step
Keep an index next into the arrivals list and a tick counter. Loop while
there are arrivals left or jobs waiting. Inside, use a second loop that adds
arrivals.get(next) while its tick equals the current tick.
Show one solution
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
List<Arrival> arrivals = List.of(
new Arrival(0, new Job("A", 10)),
new Arrival(0, new Job("B", 10)),
new Arrival(1, new Job("C", 2)),
new Arrival(3, new Job("D", 1)),
new Arrival(5, new Job("E", 5)));
System.out.println(run(arrivals));
System.out.println(run(List.of()));
}
static List<String> run(List<Arrival> arrivals) {
Comparator<Job> byMinutes = Comparator.comparingInt(Job::minutes);
PriorityQueue<Job> waiting = new PriorityQueue<>(byMinutes.thenComparing(Job::id));
List<String> log = new ArrayList<>();
int next = 0;
int tick = 0;
while (next < arrivals.size() || !waiting.isEmpty()) {
while (next < arrivals.size() && arrivals.get(next).tick() == tick) {
waiting.add(arrivals.get(next).job());
next++;
}
if (!waiting.isEmpty()) {
log.add(tick + ":" + waiting.remove().id());
}
tick++;
}
return log;
}
}
record Job(String id, int minutes) {}
record Arrival(int tick, Job job) {}Expected output:
[0:A, 1:C, 2:B, 3:D, 5:E]
[]At tick 0, A and B tie on 10 minutes and the ID breaks the tie. At tick 1, C
arrives and is shorter than the waiting B, so B waits again. That overtaking is
what the queue is for. Tick 4 logs nothing because the queue is empty and E
has not arrived, which is why the loop condition checks both the arrivals and
the queue: checking only !waiting.isEmpty() would stop at tick 4 and lose E.
Change it and test again
Add empty and one-job cases. Remove the ID tie-breaker and test different arrival orders; a single lucky output does not establish a tie guarantee. Compare the final output to sorting a copy of the list. A queue is useful when work arrives over time; sorting may be simpler for a one-off complete report.
Explain before moving on
Why is a priority queue not the same thing as a sorted list? Which operation changes its size? Explain how an explicit tie-breaker turns an accidental report order into a contract you can test.
Completion is saved in this browser only. It does not measure mastery.