Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (4k points)

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

1 Answer

0 votes
by (46k 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

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...