gpt4 book ai didi

java-8 - 如何将 Java 8 流收集到 Guava ImmutableCollection 中?

转载 作者:行者123 更新时间:2023-12-03 05:17:59 25 4
gpt4 key购买 nike

我想执行以下操作:

List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList());

但在某种程度上,结果列表是 Guava 的 ImmutableList 的实现。

我知道我能做到

List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList());
List<Integer> immutableList = ImmutableList.copyOf(list);

但我想直接收集。我试过了

List<Integer> list = IntStream.range(0, 7)
.collect(Collectors.toCollection(ImmutableList::of));

但它抛出了异常:

java.lang.UnsupportedOperationException at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:96)

最佳答案

Alexis 接受的答案中的 toImmutableList() 方法现在包含在 Guava 21 中并可用作:

ImmutableList<Integer> list = IntStream.range(0, 7)
.boxed()
.collect(ImmutableList.toImmutableList());

编辑:ImmutableList.toImmutableList 中删除了 @Beta 以及 Release 27.1 中的其他常用 API (6242bdd)。

关于java-8 - 如何将 Java 8 流收集到 Guava ImmutableCollection 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com