Java 10 · Topic 2 of 2
copyOf and unmodifiable collectors
Definition​
Java 10 added List.copyOf, Set.copyOf and Map.copyOf to make an immutable copy of an existing collection. It also added Collectors.toUnmodifiableList, toUnmodifiableSet and toUnmodifiableMap for streams.
Example code​
Copying a list and collecting a stream into an immutable list
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Demo {
public static void main(String[] args) {
List<String> mutable = new ArrayList<>(List.of("a", "b"));
List<String> copy = List.copyOf(mutable); // immutable snapshot
mutable.add("c");
System.out.println(copy); // unchanged
List<Integer> squares = List.of(1, 2, 3).stream()
.map(n -> n * n)
.collect(Collectors.toUnmodifiableList());
System.out.println(squares);
try {
squares.add(16);
} catch (UnsupportedOperationException e) {
System.out.println("cannot change it");
}
}
}
// Output:
// [a, b]
// [1, 4, 9]
// cannot change it
Finished this page? Track your progress (saved only in your browser).