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.toUnmodifiableList
Yes, there is a way:
Collectors.toUnmodifiableList
Like
List.copyOf
, this feature is built into Java 10 and later. In contrast,Collectors.toList
appeared with the debut ofCollectors
in Java 8.In your example code, just change that last part
toList
totoUnmodifiableList
.Set
andMap
tooThe
Collectors
utility class offers options for collecting into an unmodifiableSet
orMap
as well asList
.Collectors.toUnmodifiableList()
Collectors.toUnmodifiableSet()
Collectors.toUnmodifiableMap()
(or withBinaryOperator
)