Skip to main content
2 of 7
added 21 characters in body
user avatar
user avatar

You can use the overloaded version of toArray and pass a constructor reference to it:

Stream<String> stream = ...; String[] stringArray = streamString.toArray(String[]::new); 

The purpose of the IntFunction<A[]> generator parameter passed to toArray is to consume an int (the size of the array) to produce a new array. In this particular case, the generator used is an array constructor reference (String[]::new), which does just that - takes the size as a parameter and returns a new array of that size.

Example code:

Stream<String> streamString = Stream.of("a", "b", "c"); String[] stringArray = streamString.toArray(String[]::new); Arrays.stream(stringArray).forEach(System.out::println); 

Prints:

a b c 

Another option is to use an explicit lambda expression with a string array constructor:

String[] stringArray = stream.toArray(size -> new String[size]); 
skiwi
  • 69.8k
  • 32
  • 140
  • 225