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, let's create a list of strings 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. For example:
Stream<String> myNewStream = stringStream.map(s -> s.toUpperCase()); And finally convert it to a Java 8 Array using these methods:
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);Lambda expression
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);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.