Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Set.retainAll()

Keeps only the elements that are also in another collection (intersection).

Available since: Java 1.2

Syntax

boolean retainAll(Collection<?> c)

Parameters

ParameterTypeDescription
cCollection<?>The elements to keep.

Return value

boolean`true` if the set changed.

Examples

Skills two candidates have in common:

void main() {
    Set<String> anna = Set.of("java", "sql", "docker");
    Set<String> oleg = Set.of("java", "docker", "go");
    Set<String> common = new TreeSet<>(anna);
    common.retainAll(oleg);
    IO.println(common);
}

Output:

[docker, java]

Notes

The method is declared in Collection and works on lists too. It changes the collection it is called on, so to intersect two unmodifiable sets create a modifiable copy first.

See also

  • Set.removeAll() — Removes all elements of another collection from a set (difference).
  • Set.addAll() — Merges a set with another collection (union).
  • Set.contains() — Checks whether a set contains an element.

Related recipes

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.