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.

Programmer DD
Programmer DD
Programmer DD
Simplify Immutable Collections in Java: From Collections.unmodifiable to List.of & Set.of

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJava 9Immutable CollectionsList.ofSet.of
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.