Core Java
Java 10: Collecting a Stream into an Unmodifiable Collection
Java 10 introduces several new methods to facilitate the creation of unmodifiable collections.
The List.copyOf, Set.copyOf, and Map.copyOf methods create new collection instances from existing instances. For example:
List<String> modifiable = Arrays.asList("foo", "bar");
List<String> unmodifiableCopy = List.copyOf(list);
// Note that since Java 9, you can also use "of" to create
// unmodifiable collections
List<String> unmodifiable = List.of("foo", "bar");There are also new collector methods, toUnmodifiableList, toUnmodifiableSet, and toUnmodifiableMap, to allow the elements of a stream to be collected into an unmodifiable collection. For example:
// Java 10
Stream.of("foo", "bar").collect(toUnmodifiableList());
// before Java 10
Stream.of("foo", "bar").collect(
collectingAndThen(toList(), Collections::unmodifiableList));| Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 10: Collecting a Stream into an Unmodifiable Collection Opinions expressed by Java Code Geeks contributors are their own. |

