java-10中的Collectors.toUnmodifiableList

Eug*_*ene 13 java java-stream java-10

如何创建Unmodifiable列表/集/映射Collectors.toList/toSet/toMap,因为toList(等)文档为:

返回的List 的类型,可变性,可序列化或线程安全性无法保证

之前的java-10,你必须提供一个FunctionCollectors.collectingAndThen,例如:

 List<Integer> result = Arrays.asList(1, 2, 3, 4)
            .stream()
            .collect(Collectors.collectingAndThen(
                    Collectors.toList(),
                    x -> Collections.unmodifiableList(x)));
Run Code Online (Sandbox Code Playgroud)

Eug*_*ene 10

使用Java 10,这更容易,更易读:

List<Integer> result = Arrays.asList(1, 2, 3, 4)
            .stream()
            .collect(Collectors.toUnmodifiableList());
Run Code Online (Sandbox Code Playgroud)

在内部,它与之相同Collectors.collectingAndThen,但返回ListJava 9中添加的不可修改的实例.


Nam*_*man 7

此外,为了清除两个(collectingAndThenvs toUnmodifiableList)实现之间的文档差异:

Collectors.toUnmodifiableList会返回不允许空值,并会抛出一个收藏家NullPointerException,如果它呈现一个null值.

static void additionsToCollector() {
    // this works fine unless you try and operate on the null element
    var previous = Stream.of(1, 2, 3, 4, null)
            .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

    // next up ready to face an NPE
    var current = Stream.of(1, 2, 3, 4, null).collect(Collectors.toUnmodifiableList());
}
Run Code Online (Sandbox Code Playgroud)

此外,这是因为前者构造了一个实例,Collections.UnmodifiableRandomAccessList而后者构造了一个实例,ImmutableCollections.ListN该实例添加了使用静态工厂方法带到表中的属性列表.

  • 是的,但这确实是`List.of`之类的属性,仍然是+1 (2认同)