如何将Java 8流收集到Guava ImmutableCollection中? [英] How can I collect a Java 8 stream into a Guava ImmutableCollection?

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

问题描述

我想执行以下操作:

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

但是结果列表是Guava的 ImmutableList <的实现方式/ code>。

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)

java.lang.UnsupportedOperationException at 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());

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆