Queue and Deque

Queue Methods

ActionThrows exceptionReturns special value
Insertadd(e)offer(e) (false)
Remove headremove()poll() (null)
Look at headelement()peek() (null)

FIFO Queue and Stack with ArrayDeque

Example

ArrayDeque works as a queue (first in, first out) and as a stack (last in, first out). It is faster than the legacy Stack class.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Queue<String> tickets = new ArrayDeque<>();
        tickets.offer("T1");
        tickets.offer("T2");
        tickets.offer("T3");
        System.out.println("Next ticket: " + tickets.peek());
        while (!tickets.isEmpty()) {
            System.out.println("Serving " + tickets.poll());
        }

        Deque<String> history = new ArrayDeque<>();     // browser back button
        history.push("home");
        history.push("products");
        history.push("cart");
        System.out.println("Current page: " + history.peek());
        System.out.println("Back -> " + history.pop() + " closed, now on " + history.peek());

        Deque<Integer> both = new ArrayDeque<>();
        both.offerFirst(2);
        both.offerFirst(1);
        both.offerLast(3);
        System.out.println("Deque: " + both + " first=" + both.peekFirst() + " last=" + both.peekLast());
    }
}

Output

Next ticket: T1
Serving T1
Serving T2
Serving T3
Current page: cart
Back -> cart closed, now on products
Deque: [1, 2, 3] first=1 last=3

PriorityQueue

Example

A PriorityQueue always hands out the smallest element first (or by a Comparator). Hospitals, job schedulers and delivery dispatch use this idea.

import java.util.Comparator;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for (int n : new int[] { 42, 7, 19, 3, 25 }) {
            minHeap.offer(n);
        }
        System.out.print("Smallest first: ");
        while (!minHeap.isEmpty()) {
            System.out.print(minHeap.poll() + " ");
        }
        System.out.println();

        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
        maxHeap.addAll(java.util.List.of(42, 7, 19, 3, 25));
        System.out.println("Top 2 largest: " + maxHeap.poll() + ", " + maxHeap.poll());
    }
}

Output

Smallest first: 3 7 19 25 42 
Top 2 largest: 42, 25