Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Java 8 IntStream to a List?

Tags:

java

java-8

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?

like image 562
Eric Wilson Avatar asked May 15 '14 09:05

Eric Wilson


People also ask

Can we convert set object to list in Java?

We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.

Can set be converted to list?

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.


2 Answers

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 intInteger 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()  
like image 74
Ian Roberts Avatar answered Oct 07 '22 10:10

Ian Roberts


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()); 
like image 24
Ida Bucić Avatar answered Oct 07 '22 10:10

Ida Bucić