In Java, peek() returns the head of an ArrayDeque without removing it. If the deque is empty, it returns null.
It is the same as peekFirst(), and it works for both roles of a deque: in a queue it shows the next element poll() would return, and in a stack it shows the top that pop() would remove.
An instance method of java.util.ArrayDeque (Java 1.6+): a resizable-array deque with no capacity limit, no null elements, and no thread safety.
Syntax
Call peek with no arguments.
Java
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
Integer top = stack.peek(); // 20, nothing removed
Call
What it does
deque.peek()
Returns the head, or null if empty.
deque.element()
Returns the head; throws if empty.
deque.peekFirst()
Same as peek().
deque.peekLast()
Returns the tail instead.
peek() is declared in both Queue and Deque, so it is available whichever interface type you use for the variable.
Library declarations
Java
// java.util.ArrayDeque<E>
public E peek()
// Declared in Queue<E> and Deque<E>
Parameters
Parameter
Description
None
peek() takes no parameters.
Return Value
Return Value
Description
E
The head of the deque, left in place.
null
If the deque is empty.
Throw or Return a Special Value?
Each end has a method that throws when it cannot work (such as on an empty deque) and one that returnsnull or false instead. The highlighted cell matches peek().