PriorityQueue<E> · Java

peek / element

Returns the head without removing it.

public E peek(); public E element()

Complexity

Best caseO(1)
Worst caseO(1)
Extra spaceO(1)

The documented complexity: constant time for peek, element and size.

Tested example

PriorityQueue<Integer> heap = new PriorityQueue<>(List.of(4, 2, 9));
assert heap.peek() == 2; // constant time, nothing removed
assert heap.size() == 3;
// Iterating (or printing) shows the internal array order, not priority order.
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/PriorityQueueExamples.java

Behaviour

Returns
The least element; peek returns null when empty.
Errors and preconditions
element(): NoSuchElementException when empty.
Changes
Nothing.
Memory and invalidation
No allocation.