Set.removeAll()
Removes all elements of another collection from a set (difference).
Available since: Java 1.2
Syntax
boolean removeAll(Collection<?> c)Parameters
| Parameter | Type | Description |
|---|---|---|
| c | Collection<?> | The elements to remove. |
Return value
boolean`true` if the set changed.
Examples
Who in a group has not handed in the work yet:
void main() {
Set<String> group = new TreeSet<>(Set.of("Anna", "Oleg", "Ivan", "Maria"));
Set<String> submitted = Set.of("Oleg", "Maria");
group.removeAll(submitted);
IO.println(group);
}Output:
[Anna, Ivan]Notes
Like retainAll(), the method exists on every collection and changes it. On a list removeAll() deletes every occurrence of each value, not only the first one.
See also
- Set.retainAll() — Keeps only the elements that are also in another collection (intersection).
- Set.addAll() — Merges a set with another collection (union).
- Collection.removeIf() — Removes all collection elements that match a condition.
In the tutorial
- Sets: Set — Sets in Java: HashSet without duplicates, LinkedHashSet and TreeSet with ordering, union and intersection of sets.