Immutable set creation
Code Comparison
Set<String> set =
Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList("a", "b", "c")
)
);
Set<String> set =
Set.of("a", "b", "c");
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
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