PriorityQueue<E> · Java

poll / remove()

Removes and returns the head (the least element).

public E poll(); public E remove()

Complexity

Worst caseO(log n)
Extra spaceO(1)

Move the last element to the root and sift it down.

Tested example

PriorityQueue<String> queue = new PriorityQueue<>(List.of("c", "a", "b"));
assert queue.poll().equals("a");
assert queue.poll().equals("b");
assert queue.poll().equals("c");
assert queue.poll() == null; // empty: null (remove() would throw)
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 head; poll returns null when empty.
Errors and preconditions
remove(): NoSuchElementException when empty.
Changes
size decreases by 1.
Memory and invalidation
No allocation.