Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Set.of()

Creates an unmodifiable set from the listed elements.

Available since: Java 9

Syntax

static <E> Set<E> of(E... elements)

Parameters

ParameterTypeDescription
elementsE...The set elements; duplicates and `null` are forbidden.

Return value

Set<E>An unmodifiable set.

Examples

A quick membership check:

void main() {
    Set<String> vowels = Set.of("a", "e", "i", "o", "u");
    IO.println(vowels.contains("e"));
    IO.println(vowels.contains("x"));
}

Output:

true
false

A duplicate argument is an error:

void main() {
    try {
        Set.of("red", "green", "red");
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
}

Output:

duplicate element: red

Notes

The iteration order of such a set is unspecified and may change between program runs, so do not print it when order matters. Unlike new HashSet<>(...), duplicate arguments are not silently dropped but cause IllegalArgumentException. To remove duplicates from an existing collection use Set.copyOf().

See also

  • HashSet — A set without duplicates backed by a hash table; order is not guaranteed.
  • List.of() — Creates an unmodifiable list from the listed elements.
  • Set.copyOf() — Creates an unmodifiable set from a collection, dropping duplicates.
  • Set.contains() — Checks whether a set contains an element.

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.