Skip to main content
4 of 5
Second iteration. Used more standard formatting (as a result, the diff looks more extensive than it really is - use view "Side-by-side Markdown" to compare).
Peter Mortensen
  • 31.4k
  • 22
  • 110
  • 134

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:

  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.