问题描述
我想做以下事情:
List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList());
但在某种程度上,结果列表是 Guava 的 ImmutableList
的实现.
but in a way that the resulting list is an implementation of Guava's ImmutableList
.
我知道我能做到
List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList());
List<Integer> immutableList = ImmutableList.copyOf(list);
但我想直接收集到它.我试过了
but I would like to collect to it directly. I've tried
List<Integer> list = IntStream.range(0, 7)
.collect(Collectors.toCollection(ImmutableList::of));
但它引发了异常:
java.lang.UnsupportedOperationException在 com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:96)
推荐答案
Alexis 接受的答案中的 toImmutableList()
方法现在包含在 Guava 21 并可用作:
The toImmutableList()
method in the accepted answer of Alexis is now included in Guava 21 and can be used as:
ImmutableList<Integer> list = IntStream.range(0, 7)
.boxed()
.collect(ImmutableList.toImmutableList());
从 ImmutableList.toImmutableList
中删除 @Beta
以及 发布 27.1 (6242bdd).
Removed @Beta
from ImmutableList.toImmutableList
along with other frequently used APIs in Release 27.1 (6242bdd).
这篇关于如何将 Java 8 流收集到 Guava ImmutableCollection 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!