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
?
We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.
List Constructor with Set argument. The most straightforward way to convert a set to a list is by passing the set as an argument while creating the list. This calls the constructor and from there onwards the constructor takes care of the rest. Since the set has been converted to a list, the elements are now ordered.
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 brought the shorter toList
method. Produces an unmodifiable list. Discussed here.
theIntStream.boxed().toList()
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With