When working with Java streams, we can use a collector to produce a collection such as a stream.
For example, here we make a stream of the Month enum objects, and for each one generate a String holding the localized name of the month. We collect the results into a List of type String by calling Collectors.toList().
List < String > monthNames =
Arrays
.stream( Month.values() )
.map( month -> month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) )
.collect( Collectors.toList() )
;
monthNames.toString(): [janvier, février, mars, avril, mai, juin, juillet, août, septembre, octobre, novembre, décembre]
To make that list unmodifiable, we can call List.copyOf in Java 10 and later.
List < String > monthNamesUnmod = List.copyOf( monthNames );
➥ Is there a way for the stream with collector to produce an unmodifiable list without me needing to wrap a call to List.copyOf?
Collectors.toUnmodifiableListYes, there is a way:
Collectors.toUnmodifiableListLike
List.copyOf, this feature is built into Java 10 and later. In contrast,Collectors.toListappeared with the debut ofCollectorsin Java 8.In your example code, just change that last part
toListtotoUnmodifiableList.SetandMaptooThe
Collectorsutility class offers options for collecting into an unmodifiableSetorMapas well asList.Collectors.toUnmodifiableList()Collectors.toUnmodifiableSet()Collectors.toUnmodifiableMap()(or withBinaryOperator)