Collections beginner

Immutable set creation

Create immutable sets with a single factory call.

✕ Java 8
Set<String> set =
    Collections.unmodifiableSet(
        new HashSet<>(
            Arrays.asList("a", "b", "c")
        )
    );
✓ Java 9+
Set<String> set =
    Set.of("a", "b", "c");
📏

Concise

One line instead of three nested calls.

🚫

Detects duplicates

Throws if you accidentally pass duplicate elements.

🔒

Immutable

No add/remove possible after creation.

Old Approach
Verbose Wrapping
Modern Approach
Set.of()
Since JDK
9
Difficulty
beginner
Immutable set creation
Available

Widely available since JDK 9 (Sept 2017)

Set.of() creates a truly immutable set that rejects nulls and duplicate elements at creation time. No more wrapping mutable sets.

Share 𝕏 🦋 in