HashSet<E> · Java

remove / removeIf

Removes one element, or every element matching a predicate.

public boolean remove(Object o); default boolean removeIf(Predicate<? super E> filter)

Complexity

ExpectedO(1) for remove
Worst caseO(n) for removeIf (visits every element)
Extra spaceO(1)

remove is HashMap.remove; removeIf iterates.

Tested example

Set<Integer> values = new HashSet<>(List.of(1, 2, 3));
assert values.remove(2);
assert !values.remove(2); // missing: false
values.removeIf(x -> x > 2);
assert values.equals(Set.of(1));
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/HashSetExamples.java

Parameters

o / filter
The element or the condition.

Behaviour

Returns
Whether anything was removed.
Errors and preconditions
removeIf: NullPointerException for a null filter.
Changes
Removes elements.
Memory and invalidation
Does not shrink.