Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Set.copyOf()

Creates an unmodifiable set from a collection, dropping duplicates.

Available since: Java 10

Syntax

static <E> Set<E> copyOf(Collection<? extends E> coll)

Parameters

ParameterTypeDescription
collCollection<? extends E>The source collection; duplicates are allowed, `null` is not.

Return value

Set<E>An unmodifiable set of unique elements.

Examples

How many different values a list has:

void main() {
    List<Integer> votes = List.of(3, 1, 3, 2, 1, 3);
    Set<Integer> unique = Set.copyOf(votes);
    IO.println(unique.size());
    IO.println(unique.contains(2));
}

Output:

3
true

Notes

The order of the result is unspecified. If you need the order of first appearance use new LinkedHashSet<>(list); for sorted order use new TreeSet<>(list).

See also

  • Set.of() — Creates an unmodifiable set from the listed elements.
  • List.copyOf() — Creates an unmodifiable list copy of a collection.
  • Stream.distinct() — Removes duplicate elements from a stream.

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.