Queue.peek()
Returns the head of a queue without removing it.
Available since: Java 1.5
Syntax
E peek()Return value
EThe head element without removing it, or `null` if the queue is empty.
Examples
Looking without taking:
void main() {
Queue<String> q = new ArrayDeque<>(List.of("first", "second"));
IO.println(q.peek());
IO.println(q.size());
q.clear();
IO.println(q.peek());
}Output:
first
2
nullNotes
For a stack built on ArrayDeque, peek() shows the top — the last element added with push(). The element() version throws NoSuchElementException on an empty queue.
See also
- Queue.poll() — Takes and removes the head of a queue.
- Queue.offer() — Adds an element to the tail of a queue.
- Deque.push() — Pushes an element onto the top of a stack (the head of a deque).
In the tutorial
- Queues and deques — Queues in Java: Queue and ArrayDeque, a stack built on Deque, the offer, poll and peek methods and the PriorityQueue.