How to Convert a Java 8 Stream to an Array?
Answers
Answer:
Explanation:
Java 8‘s Collectors class provides many static methods to collect objects from a stream and store them into collection. But these method does 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 primitives stream to collection, you can adapt on of following two ways.
1. IntStream to collection – boxed streams
Using boxed() method of IntStream, LongStream or DoubleStream e.g. IntStream.boxed(), you can get stream of wrapper objects which can be collected by Collectors methods.
List<Integer> ints = IntStream.of(1,2,3,4,5)
.boxed()
.collect(Collectors.toList());
System.out.println(ints);
Output:
[1, 2, 3, 4, 5]
2. IntStream to list – map int to Integer
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.
List<Integer> ints = IntStream.of(1,2,3,4,5)
.mapToObj(Integer::valueOf)
.collect(Collectors.toList());
System.out.println(ints);
Output:
[1, 2, 3, 4, 5]
3. Convert IntStream to array
It is also useful to know how to convert primitive stream to array. Use IntStream.toArray() method to convert from int stream to array.
int[] intArray = IntStream.of(1, 2, 3, 4, 5).toArray();
System.out.println(Arrays.toString(intArray));
Output:
[1, 2, 3, 4, 5]
Similarly, use toArray() function of LongStream or DoubleStream as well.