You can convert a java 8 stream to an array using this simple code block:
String[] myNewArray3 = myNewStream.toArray(String[]::new); But let's explain things more first lets
Create a list of string filled with three values :
String[] stringList = {"Bachiri","Taoufiq","Abderrahman"}; Create a stream from the given Array :
Stream<String> stringStream = Arrays.stream(stringList); we can now perform some operations on this stream Ex:
Stream<String> myNewStream = stringStream.map(s -> s.toUpperCase()); and finally convert to java 8 Array using this methods :
1-Classic method (Functional interface)
IntFunction<String[]> intFunction = new IntFunction<String[]>() { @Override public String[] apply(int value) { return new String[value]; } }; String[] myNewArray = myNewStream.toArray(intFunction); 2 -Lambda expression
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]); 3- Method reference
String[] myNewArray3 = myNewStream.toArray(String[]::new); Method reference Explanation:
It's another way of writing a lambda expression that it's strictly equivalent to the other.