Reading history

Java Queue, Deque and PriorityQueue

6 min read 0 views

Learn Java queues: FIFO with offer, poll and peek, ArrayDeque as a stack, double-ended deques, and PriorityQueue min-heaps, max-heaps and custom priorities.

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 Queue interface: offer, poll and peek
  • Using ArrayDeque as a stack with push and pop
  • Adding and removing at both ends of a Deque
  • PriorityQueue as 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 Queue is FIFO (first in, first out), like a ticket line. offer adds at the back, poll removes from the front, and peek looks at the front without removing it.
  • poll and peek return null on an empty queue. The alternative methods remove and element throw an exception instead.
  • A Deque used with push and pop is a stack: LIFO (last in, first out), like the browser’s back button. pop returned “java”, the last page pushed.
  • offerFirst, offerLast, pollFirst and pollLast work at either end, so one ArrayDeque can be a queue, a stack, or both.
  • Prefer ArrayDeque over the old Stack class and, for most queues, over LinkedList. It is faster and uses less memory. It does not accept null elements.

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 PriorityQueue is a heap. poll always 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 peek takes O(1). That makes priority queues the standard tool for scheduling, “top K” problems and Dijkstra’s shortest-path algorithm.

Which One to Use

NeedUseMain methods
First in, first outArrayDeque as a Queueoffer, poll, peek
Last in, first out (stack)ArrayDeque as a Dequepush, pop, peek
Both endsArrayDequeofferFirst/Last, pollFirst/Last
Most important firstPriorityQueueoffer, poll, peek
Shared between threadsArrayBlockingQueue, LinkedBlockingQueueput, take

Common Mistakes

  1. Expecting a printed PriorityQueue to be sorted. Poll the elements one by one to get sorted order.
  2. Using remove() on an empty queue, which throws NoSuchElementException. Use poll() and check for null.
  3. Using java.util.Stack, an old synchronised class. Use ArrayDeque.
  4. 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: offer at the back, poll from the front.
  • ArrayDeque is the go-to queue and stack.
  • PriorityQueue always returns the smallest (or highest-priority) element.
  • Give a comparator to change the priority order.

Next: Java Optional.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *