Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Set.remove()

Removes an element from a set.

Available since: Java 1.2

Syntax

boolean remove(Object o)

Parameters

ParameterTypeDescription
oObjectThe element to remove.

Return value

boolean`true` if the element was in the set.

Examples

Removing a present and an absent element:

void main() {
    Set<String> online = new TreeSet<>(List.of("Anna", "Oleg", "Ivan"));
    IO.println(online.remove("Oleg"));
    IO.println(online.remove("Maria"));
    IO.println(online);
}

Output:

true
false
[Anna, Ivan]

Notes

An absent element is not an error — the method simply returns false. To remove all elements matching a condition use removeIf().

See also

  • Set.add() — Adds an element if it is not in the set yet.
  • Set.removeAll() — Removes all elements of another collection from a set (difference).
  • 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.

Thanks for reading!

Donate to the site — we work hard for you.