How do I convert a Java 8 IntStream to a List?
I'm looking at the docs for the IntStream
, and I see an toArray
method, but no way to go directly to a List<Integer>
Surely there is a way to convert a Stream
to a List
?
Solution 1:
IntStream::boxed
IntStream::boxed
turns an IntStream
into a Stream<Integer>
, which you can then collect
into a List
:
theIntStream.boxed().collect(Collectors.toList())
The boxed
method converts the int
primitive values of an IntStream
into a stream of Integer
objects. The word "boxing" names the int
⬌ Integer
conversion process. See Oracle Tutorial.
Java 16 and later
Java 16 brought the shorter toList
method. Produces an unmodifiable list. Discussed here.
theIntStream.boxed().toList()
Solution 2:
You could also use mapToObj() on a Stream, which takes an IntFunction and returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.
List<Integer> intList = myIntStream.mapToObj(i->i).collect(Collectors.toList());
Solution 3:
You can use primitive collections available in Eclipse Collections and avoid boxing.
MutableIntList list =
IntStream.range(1, 5)
.collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);
Note: I am a contributor to Eclipse Collections.
Solution 4:
You can use the collect method:
IntStream.of(1, 2, 3).collect(ArrayList::new, List::add, List::addAll);
In fact, this is almost exactly what Java is doing when you call .collect(Collectors.toList()) on an object stream:
public static <T> Collector<T, ?, List<T>> toList() {
return new Collectors.CollectorImpl(ArrayList::new, List::add, (var0, var1) -> {
var0.addAll(var1);
return var0;
}, CH_ID);
}
Note: The third parameter is only required if you want to run parallel collection; for sequential collection providing just the first two will suffice.