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

Java 8 code to convert Stream<T> to array of type T
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));
 }
}
 OUTPUT of the above code
[Red, Blue, Green, Orange, Yellow]

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 –

String[] stringArray=stringStream.toArray(size -> new String[size])

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.

 

Digiprove sealCopyright ¬© 2014-2019 JavaBrahman.com, all rights reserved.