问题
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
?
回答1:
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 of Collectors in Java 8.
In your example code, just change that last part toList to toUnmodifiableList
.
List < String > monthNames =
Arrays
.stream( Month.values() )
.map( month -> month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) )
.collect( Collectors.toUnModifiableList() ) // 🡄 Call `toUnModifiableList`.
;
Set
and Map
too
The Collectors utility class offers options for collecting into an unmodifiable Set
or Map
as well as List
.
- Collectors.toUnmodifiableList()
- Collectors.toUnmodifiableSet()
- Collectors.toUnmodifiableMap() (or with BinaryOperator)
回答2:
In Java 8 we could use Collectors.collectingAndThen.
List < String > monthNames =
Arrays
.stream( Month.values() )
.map( month -> month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) )
.collect(
Collectors.collectingAndThen(Collectors.toList(),
Collections::unmodifiableList)
)
;
来源:https://stackoverflow.com/questions/61132631/can-the-list-returned-by-a-java-streams-collector-be-made-unmodifiable