Convert Stream to Array using Stream toArray() in Java
Convert Stream to Array
To get a stream from an array, we use Stream.of(array) method.
Similary, to get an array from a stream, you can use Stream.toArray() function.
The toArray() function returns an array containing the elements processed by the stream.
Convert Stream to Array of Integers
Integer[] arr1 = Stream.of(1,2,3,4,5).toArray(Integer[]::new); System.out.println(Arrays.toString(arr1));
Output:
[1, 2, 3, 4, 5]
Convert Stream to Array of Strings
String[] arr2 = Stream.of("ABC","DEF","GHI").toArray(String[]::new); System.out.println(Arrays.toString(arr2));
Output:
[ABC, DEF, GHI]
Converting Stream to List using toArray()
For converting Stream to List, one option is to convert the stream into an array, and then using Arrays.asList(Array) to get the desired list.
The result will be a fixed-sized (but not immutable) list of all the stream elements.
List<Object> list = Arrays.asList(Stream.of("ABC","DEF","GHI").toArray()); System.out.println(list);
Output:
[ABC, DEF, GHI]
You may also like
Convert Stream to List using Stream collect(toList())
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post