Java 流收集器返回的列表可以不可修改吗?

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

使用 Java 流时,我们可以使用收集器来生成流等集合。

例如,这里我们创建了一个 Month 枚举对象流,并为每个对象生成一个 String 保存月份的本地化名称。我们通过调用 Collectors.toList().

将结果收集到类型 StringList
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]

在 Java 10 及更高版本中实现 list unmodifiable, we can call List.copyOf

List < String > monthNamesUnmod = List.copyOf( monthNames );

➥ 有没有一种方法可以让带有收集器的流生成一个不可修改的列表,而我不需要包装对 List.copyOf 的调用?

Collectors.toUnmodifiableList

是的,有办法:Collectors.toUnmodifiableList

喜欢List.copyOf, this feature is built into Java 10 and later. In contrast, Collectors.toList appeared with the debut of Collectors in Java 8

在您的示例代码中,只需将最后一部分 toList 更改为 toUnmodifiableList

List < String > monthNames = 
        Arrays
        .stream( Month.values() )
        .map( month -> month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) )
        .collect( Collectors.toUnModifiableList() )  //  Call `toUnModifiableList`.
;

SetMap

Collectors 实用程序 class 提供了用于收集到不可修改的 SetMap 以及 List.

的选项

在 Java 8 中我们可以使用 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) 
        )
;