Convert Stream to Array in Java 8

To convert a Stream to an array, there is an overloaded version of toArray() method for Stream objects. The toArray(IntFunction<A[]> generator) method returns an array containing the elements of this stream, using the provided generator function to allocate the returned array.

String[] stringArr = { "a", "b", "c", "d" };
Stream<String> stream = Stream.of(stringArr);
String[] arr = stream.toArray(size -> new String[size]);
System.out.println(Arrays.toString(arr));

We can also use the method reference format which does exactly the same thing.

String[] arr = stream.toArray(String[]::new);

Leave a Comment