Can the list returned by a Java streams collector be made unmodifiable?

1.1k views Asked by At

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?

2

There are 2 answers

0
Basil Bourque On BEST ANSWER

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.

1
jaco0646 On

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) 
        )
;