Queues And Deques
A queue serves elements first in, first out, like a line at a counter. A stack works the other way round: the last element added is the first one out. A Deque supports both ends, so it can act as either.
ArrayDeque is a good default for in-memory queue and stack work. Adding at one end and removing at the other makes the order explicit.
Serve in arrival order
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque<String> orders = new ArrayDeque<>();
orders.offerLast("A12");
orders.offerLast("A13");
System.out.println("Next: " + orders.peekFirst());
System.out.println("Served: " + orders.pollFirst());
System.out.println("Next: " + orders.peekFirst());
}
}
Output:
Next: A12
Served: A12
Next: A13
Both orders enter at the back. peekFirst checks the next order without removing it, while pollFirst removes the order being served.
Jump to the front
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque<String> orders = new ArrayDeque<>();
orders.addLast("A12");
orders.addLast("A13");
orders.addFirst("A01");
System.out.println(orders);
System.out.println("Served: " + orders.removeFirst());
System.out.println(orders);
}
}
Output:
[A01, A12, A13]
Served: A01
[A12, A13]
addLast adds at the back like offerLast, while addFirst places an urgent order at the front, ahead of everyone waiting. removeFirst takes the front element off.
removeFirst throws an exception on an empty deque. pollFirst returns null instead, which suits code where an empty queue is an expected condition.
Add Medic to the front of the line, then remove everyone from the front in order.