Immutable set creation
Create immutable sets with a single factory call.
Code Comparison
✕ Java 8
Set<String> set =
Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList("a", "b", "c")
)
);
✓ Java 9+
Set<String> set =
Set.of("a", "b", "c");
See a problem with this code? Let us know.
Why the modern way wins
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
JDK Support
Immutable set creation
Available
Widely available since JDK 9 (Sept 2017)
How it works
Set.of() creates a truly immutable set that rejects nulls and duplicate elements at creation time. No more wrapping mutable sets.
Related Documentation
Proof