Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I collect a Java 8 stream into a Guava ImmutableCollection?

I would like to do the following:

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

but in a way that the resulting list is an implementation of Guava's ImmutableList.

I know I could do

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

but it threw an exception:

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

like image 630
Zoltán Avatar asked Mar 12 '15 15:03

Zoltán


People also ask

How do I reuse a stream in Java 8?

In Java 8, Stream cannot be reused, once it is consumed or used, the stream will be closed.

How do you make a collection immutable in Java 8?

In Java 8 and earlier versions, we can use collection class utility methods like unmodifiableXXX to create immutable collection objects. If we need to create an immutable list then use the Collections. unmodifiableList() method.


1 Answers

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

Edit: Removed @Beta from ImmutableList.toImmutableList along with other frequently used APIs in Release 27.1 (6242bdd).

like image 82
Ritesh Avatar answered Oct 09 '22 07:10

Ritesh