Course contentsShow
← Java
Lesson 1187 of 2,87027. Queue and Deque ImplementationsFree lesson

Retrieving the Head: peek and poll

Use peek to inspect the highest-priority element without removal, and poll to retrieve and remove it.

Retrieving the Head: peek and poll

You'll learn how to inspect and remove the highest-priority element from a PriorityQueue using peek and poll.

The Core Idea

In a PriorityQueue, the "head" is the element with the highest priority according to your ordering (natural or custom comparator). You have two ways to work with this element:

  • peek() lets you look at the head without removing it — like peeking at the next customer in line without calling them forward
  • poll() retrieves and removes the head — like serving the next customer and having them leave the line

Think of it like a waiting room at a doctor's office. You can peek at the clipboard to see who's next (peek), or you can actually call that person in and remove their name from the list (poll).

How They Work

peek() returns the head element or null if the queue is empty. The queue remains unchanged.

poll() returns the head element and removes it from the queue. If the queue is empty, it returns null. After removal, the next-highest-priority element automatically becomes the new head.

PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(5);
queue.offer(2);
queue.offer(8);

Integer head = queue.peek();  // Returns 2, queue still contains [2, 5, 8]
Integer head2 = queue.peek(); // Returns 2 again

Integer served = queue.poll(); // Returns 2, removes it: now [5, 8]
Integer next = queue.poll();   // Returns 5, removes it: now [8]

When to Use Each

Use peek() when you need to check what's next without commitment. Use poll() when you're ready to process and remove the highest-priority item.

Key Takeaway: Use peek() to inspect the highest-priority element without removal, and poll() to retrieve and remove it — both return null on empty queues.