Java Collectors class provides many static methods to collect items from a Stream and store them into a Collection. But these methods do not work with streams of primitives.
//It works perfect !!
List<String> strings = Stream.of("how", "to", "do", "in", "java")
.collect(Collectors.toList());
//Compilation Error !!
IntStream.of(1,2,3,4,5).collect(Collectors.toList());
To convert the Stream of primitives to a Collection, we can adapt one of the following ways. Note that these methods can be applied to all three primitive streams i.e. IntStream, LongStream, and DoubleStream.
1. Collecting IntStream into Collection using Boxed Stream
Using boxed()
method of IntStream
, LongStream
or DoubleStream
e.g. IntStream.boxed(), we can get stream of wrapper objects which can be collected by Collectors
methods.
//Primitive Stream -> List
List<Integer> listOfIntegers = IntStream.of(1,2,3,4,5)
.boxed()
.collect(Collectors.toList());
List<Long> listOfLongs = LongStream.of(1,2,3,4,5)
.boxed()
.collect(Collectors.toList());
List<Double> listOfDoubles = DoubleStream.of(1.0,2.0,3.0,4.0,5.0)
.boxed()
.collect(Collectors.toList());
2. Collecting IntStream to List by Mapping to Objects
Another way is to manually to the boxing using IntStream.mapToObj(), IntStream.mapToLong() or IntStream.mapToDouble() methods. There are other similar methods in other stream classes, which you can use.
//Primitive Stream -> List List<Integer> listOfIntegers = IntStream.of(1,2,3,4,5) .mapToObj(Integer::valueOf) .collect(Collectors.toList()); List<Long> listOfLongs = LongStream.of(1,2,3,4,5) .mapToObj(Long::valueOf) .collect(Collectors.toList()); List<Double> listOfDoubles = DoubleStream.of(1.0,2.0,3.0,4.0,5.0) .mapToObj(Double::valueOf) .collect(Collectors.toList());
3. Collecting IntStream to Array
It is also useful to know how to convert the primitive stream to an array. Use IntStream.toArray()
method to convert from int stream to array.
int[] intArray = IntStream.of(1, 2, 3, 4, 5).toArray(); long[] longArray = LongStream.of(1, 2, 3, 4, 5).toArray(); double[] doubleArray = DoubleStream.of(1, 2, 3, 4, 5).toArray();
Similarly, use toArray()
function of LongStream
or DoubleStream
as well.
Happy Learning !!