Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Set.addAll()

Merges a set with another collection (union).

Available since: Java 1.2

Syntax

boolean addAll(Collection<? extends E> c)

Parameters

ParameterTypeDescription
cCollection<? extends E>The collection of elements to add.

Return value

boolean`true` if the set changed.

Examples

The union of two sets:

void main() {
    Set<String> union = new TreeSet<>(Set.of("java", "sql"));
    union.addAll(Set.of("sql", "git"));
    IO.println(union);
}

Output:

[git, java, sql]

Notes

The method changes the set it is called on. To keep the source data intact, copy it first: new HashSet<>(a), then addAll(b). retainAll() gives the intersection and removeAll() the difference.

See also

  • Set.retainAll() — Keeps only the elements that are also in another collection (intersection).
  • Set.removeAll() — Removes all elements of another collection from a set (difference).
  • List.addAll() — Adds all elements of another collection to a list.

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.