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

JavaJava 8

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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 - Java

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 - Java

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.

Solution 5 - Java

Find the folowing example of finding square of each int element using Java 8 :-

IntStream ints = Arrays.stream(new int[] {1,2,3,4,5});		 
List<Integer> intsList = ints.map(x-> x*x)
          .collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric WilsonView Question on Stackoverflow
Solution 1 - JavaIan RobertsView Answer on Stackoverflow
Solution 2 - JavaIda BucićView Answer on Stackoverflow
Solution 3 - JavaNikhil NanivadekarView Answer on Stackoverflow
Solution 4 - JavaHarry JonesView Answer on Stackoverflow
Solution 5 - JavaVikashView Answer on Stackoverflow