Simplify Immutable Collections in Java: From Collections.unmodifiable to List.of & Set.of
This article demonstrates how to create immutable collections in Java, comparing traditional approaches using Collections.unmodifiableSet/List with Java 8 Stream‑based methods and the concise Java 9 factory methods Set.of, List.of, and Map.of, and explains key differences between List.of and Arrays.asList.
Conventional Approach
Before Java 9, immutable collections were created by constructing a mutable collection and then wrapping it with Collections.unmodifiableSet or Collections.unmodifiableList:
// immutable Set
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("c");
set = Collections.unmodifiableSet(set);
// immutable List
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list = Collections.unmodifiableList(list);Java 8 Style
Using the Stream API, the code can be shortened:
Set<String> set = Collections.unmodifiableSet(Stream.of("a", "b", "c").collect(toSet()));
List<Integer> list = Collections.unmodifiableList(Stream.of(1, 2, 3).collect(toList()));Java 9 Style
Java 9 introduces factory methods that create immutable collections directly:
Set<String> set = Set.of("a", "b", "c");
List<Integer> list = List.of(1, 2, 3);Complex collections such as maps are also supported:
Map<String, String> map = Map.of("a", "1", "b", "2", "c", "3");Note that Map.of requires an even number of arguments, each pair representing a key and a value:
Map.of()
Map.of(k1, v1)
Map.of(k1, v1, k2, v2)
Map.of(k1, v1, k2, v2, k3, v3)
...Difference from Arrays.asList
Key differences between List.of (introduced in Java 9) and Arrays.asList are: List.of creates an immutable collection, whereas Arrays.asList returns a mutable list backed by an array.
Both prohibit add and remove, but Arrays.asList allows set to modify elements, while List.of throws java.lang.UnsupportedOperationException. List.of does not permit null elements, while Arrays.asList accepts them.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
