JB Header
Java 8 code to convert Stream to Array using Stream.toArray method
In this programming quick tip we will see the Java 8 code for converting from a java.util.stream.Stream<T> to an array of type T using Stream.toArray() method with explanation of the code. Java 8 code to convert Stream<T> to array of type T [su_box title="Java 8 code to convert Stream<T> to array of type T" style="soft" box_color="#fcba43" title_color="#00000" radius="4" Class="for-shortcodebox"][java]package com.javabrahman.java8.streams; import static java.util.stream.Collectors.toList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import com.javabrahman.java8.Employee; public class StreamToArray { public static void main(String args[]) { List<String> stringList=Arrays.asList("Red", "Blue", "Green", "Orange", "Yellow"); Stream<String> stringStream= stringList.stream(); String[] stringArray=stringStream.toArray(size -> new String[size]); System.out.println(Arrays.toString(stringArray)); } }[/java] [/su_box]  OUTPUT of the above code[su_note note_color="#1a1a1a" text_color="#DAD9D7"][Red, Blue, Green, Orange, Yellow][/su_note] Explanation of the code In the above code we invoked the method toArray() on Stream<T> interface to get an array of String like this - [su_note note_color="#ffffee" text_color="#000000"] String[] stringArray=stringStream.toArray(size -> new String[size]) [/su_note] Where,
  • The overloaded toArray() method used above is passed size -> new String[size] as the parameter which is in fact a lambda expression(read tutorialLink to Lambda Expressions Tutorial.)
  • The toArray() method accepts a lambda expression as an input parameter; toArray()’s method signature is - <A> A[] toArray(IntFunction<A[]> generator)
  • I.e. size -> new String[size] is an instance of a functional interface IntFunction<R>
  • The IntFunction<A[]> is a Java 8 Functional Interface(read tutorialClick to Read Detailed Article on Functional Interfaces) whose functional descriptor is defined as int -> R for functional method with signature R apply(int value)
  • I.e. the IntFunction<A[]> takes an int input and returns a result of type R.
  • Putting it all together, in our case, the IntFunction<A[]> has been passed the lambda expression size -> new String[size]. This lambda returns a String[] array of length size based on input size passed to it. And this String[] array is what we get back from the Stream.toArray() method as the desired result.
[su_note note_color="#fbfbc4" text_color="#000000" radius="4"][/su_note]