本文介绍了如何将Java 8流收集到Guava ImmutableCollection中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行以下操作:

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

但它引发了一个例外:


推荐答案

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

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

这篇关于如何将Java 8流收集到Guava ImmutableCollection中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:43