Queue Interface and PriorityQueue in Java

Naveen AnamaneniUpdated · 5 min read

The Queue interface in Java represents a collection that holds elements waiting to be processed. Most queues work in first-in, first-out (FIFO) order, like people standing in a line at a ticket counter. PriorityQueue is a special queue that always hands out the element with the highest priority first (by default, the smallest), no matter when it was added. In this lesson, you will learn the methods of Queue and how to use PriorityQueue.

Declaration

Declaration
public interface Queue<E> extends Collection<E>
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Methods of Queue

Each queue operation comes in two forms: one that throws an exception when it fails, and one that returns a special value instead.

OperationThrows an exceptionReturns a special value
Add at the tailadd(e)offer(e) returns false
Remove the headremove()poll() returns null
Look at the headelement()peek() returns null

In practice, offer, poll and peek are used most, because an empty queue is a normal situation, not an error.

Example: A FIFO Queue

Let's see an example of a ticket counter line.

TicketLine.java▶ Try it
import java.util.ArrayDeque;
import java.util.Queue;
 
public class TicketLine {
    public static void main(String[] args) {
        Queue<String> line = new ArrayDeque<>();
        line.offer("Navika");
        line.offer("Srihitha");
        line.offer("Advitha");
        System.out.println("Line: " + line);
        System.out.println("Next: " + line.peek());
 
        while (!line.isEmpty()) {
            System.out.println("Serving " + line.poll());
        }
        System.out.println("poll on empty: " + line.poll());
    }
}
Output
Line: [Navika, Srihitha, Advitha]
Next: Navika
Serving Navika
Serving Srihitha
Serving Advitha
poll on empty: null

Explanation: offer adds each person to the tail. peek shows who is next without removing them. poll removes from the head, so people are served in the order they arrived. On an empty queue, poll returns null instead of throwing.

PriorityQueue

A PriorityQueue doesn't serve in arrival order. It always gives out the smallest element according to natural order, or the first according to a comparator. Inside, it uses a binary heap: a tree stored in an array where every parent is smaller than its children.

The smallest element is always at the root of the heap

Features of PriorityQueue

  • Serves the smallest first (or the highest priority, using a comparator).
  • offer and poll take O(log n); peek takes O(1).
  • No null elements.
  • Printing or iterating doesn't show sorted order. Only poll returns elements in priority order.
  • Not synchronized.

Example: Hospital Triage with a Comparator

Triage.java▶ Try it
import java.util.Comparator;
import java.util.PriorityQueue;
 
public class Triage {
    record Patient(String name, int severity) { }
 
    public static void main(String[] args) {
        PriorityQueue<Patient> queue = new PriorityQueue<>(
            Comparator.comparingInt(Patient::severity).reversed());
 
        queue.offer(new Patient("Navika", 2));
        queue.offer(new Patient("Srihitha", 5));
        queue.offer(new Patient("Advitha", 3));
 
        while (!queue.isEmpty()) {
            Patient p = queue.poll();
            System.out.println(p.name() + " (severity " + p.severity() + ")");
        }
    }
}
Output
Srihitha (severity 5)
Advitha (severity 3)
Navika (severity 2)

Explanation: The comparator orders patients by severity from highest to lowest, so the most serious case is always polled first, even though Srihitha arrived second.

Example: The Three Smallest Numbers

Smallest.java▶ Try it
import java.util.List;
import java.util.PriorityQueue;
 
public class Smallest {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(
            List.of(40, 10, 30, 20, 50));
        System.out.println("Printed: " + pq);
        System.out.print("Polled:  ");
        for (int i = 0; i < 3; i++) {
            System.out.print(pq.poll() + (i < 2 ? ", " : "\n"));
        }
    }
}
Output
Printed: [10, 20, 30, 40, 50]
Polled:  10, 20, 30

Explanation: poll returns the numbers from smallest up. The printed form happens to look sorted here, but in general it shows the internal heap array, which is not guaranteed to be sorted.

Common Mistakes

Expecting PriorityQueue to be FIFO. It serves by priority, not arrival.

Printing a PriorityQueue to check its order. The heap layout isn't sorted.

Using remove() or element() on a queue that may be empty. They throw NoSuchElementException; use poll and peek.

Interview Corner

What is the difference between poll() and remove() in a Queue?

Both remove and return the head of the queue. On an empty queue, remove() throws NoSuchElementException, while poll() returns null. Similarly, element() throws and peek() returns null, and add throws on a full bounded queue while offer returns false.

How does PriorityQueue work internally?

It stores elements in an array arranged as a binary min-heap, where each parent is less than or equal to its children according to natural order or the supplied comparator. The smallest element is at index 0, so peek is O(1). offer adds at the end and sifts up, and poll moves the last element to the root and sifts down, both in O(log n).

Practice

  1. Easy: Simulate a printer queue with an ArrayDeque: add five jobs, print three, and show what's left.
  2. Harder: Use a PriorityQueue to find the 3 largest numbers in a list of 10, keeping at most 3 elements in the queue at any time.

Quick check: Queue and PriorityQueue

4 questions
1What does poll() return on an empty queue?
2Which element does a PriorityQueue of numbers poll first by default?
3What structure does PriorityQueue use internally?
4Does printing a PriorityQueue show its elements in sorted order?

Key Takeaways

Was this tutorial helpful?

Lesson 278 of 482