0 votes
1 view
in Java by (3.5k points)

What is the easiest/fastest way to change a Java 8 Stream into an array?

1 Answer

0 votes
by (41k points)

You can use the toArray(IntFunction<A[]> generator) method with an array constructor reference. Check it in the API documentation for the method.

String[] stringArray = stringStream.toArray(String[]::new);

It finds a method that takes in an integer (the size) as an argument and returns a String[], that is what actually (one of the overloads of) new String[] does.

You could also write your IntFunction:

Stream<String> stringStream = ...;

String[] stringArray = stringStream.toArray(size -> new String[size]);

The purpose of the IntFunction<A[]> generator is to change an integer, the size of the array, to a new array.

Example code:

Stream<String> stringStream = Stream.of("q", "w", "e");

String[] stringArray = stringStream.toArray(size -> new String[size]);

Arrays.stream(stringArray).forEach(System.out::println);

Prints:

q

w

e

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...