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
| Expected | O(1) for remove |
|---|---|
| Worst case | O(n) for removeIf (visits every element) |
| Extra space | O(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));
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.