Collectors.toUnmodifiableList(): Immutable Collections
You'll learn how to create truly immutable lists from streams using toUnmodifiableList(), ensuring your collected data cannot be modified after creation.
What Is toUnmodifiableList()?
Introduced in Java 10, Collectors.toUnmodifiableList() collects stream elements into an immutable list—one that cannot be modified after creation. Unlike toList(), which returns a mutable list that callers might accidentally modify, toUnmodifiableList() guarantees the result is read-only.
Think of it like laminating a document: once sealed, the contents are permanently fixed and protected from changes.
Why Use Immutable Collections?
When you collect stream results with toList(), the returned list can be modified—elements can be added, removed, or changed. This might lead to bugs if you intended the data to remain constant. With toUnmodifiableList(), any attempt to modify the list throws an UnsupportedOperationException.
Basic Syntax
List<String> names = Stream.of("Alice", "Bob", "Charlie")
.collect(Collectors.toUnmodifiableList());
// names is now immutable
// names.add("Dave"); // throws UnsupportedOperationException
When to Use It
Use toUnmodifiableList() when:
- You want to return collections from methods without worrying about external modification
- You're creating defensive copies that must remain unchanged
- You need to share data safely across multiple parts of your application
- You want compile-time guarantees that collected data won't be mutated
The Safety Advantage
Immutable collections prevent entire categories of bugs related to unintended modifications, making your code more predictable and thread-safe by default.
Key Takeaway: Collectors.toUnmodifiableList() creates immutable lists from streams, throwing exceptions on modification attempts—use it when you need guaranteed read-only results (Java 10+).