CKTIS / Java
`Queue.peek()` — inspect the queue head without removing it
Use `peek()` to read the head of a queue without removing it. If the queue is empty, the method returns `null`.
Version: Java SE 21
Syntax
E peek();
// Example call on a Queue<String>:
String head = queue.peek();Queue.peek() is an instance method of the java.util.Queue<E> interface. It takes no arguments and returns the head as a value of type E without changing the queue. The implementation defines the ordering, so the head is not necessarily the element inserted earliest.
On an empty queue, peek() returns null. The element() method also leaves the queue unchanged, but throws NoSuchElementException when it is empty. The poll() method removes and returns the head, or returns null when the queue is empty.
Avoid inserting null as a queue element. If the implementation allows it, a null result from peek() cannot distinguish an empty queue from a queue with null at its head. The example uses ArrayDeque, which does not allow null elements.
Examples
import java.util.ArrayDeque;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();
queue.offer("apple");
queue.offer("banana");
System.out.println(queue.peek());
System.out.println(queue.poll());
System.out.println(queue.peek());
queue.poll();
System.out.println(queue.peek());
}
}Result
apple apple banana null
The first `peek()` prints `apple` without removing it, so the following `poll()` also prints `apple` but removes it. The next `peek()` prints `banana`. The second `poll()` removes `banana` without printing it, and the final `peek()` prints `null`.
Related lessons
- Java · Lesson 61 · Basic · Version: 2