How to Convert a Java 8 Stream to an Array?

Java 8Object Oriented ProgrammingProgramming

To convert a stream to an Array in Java -

  • Collect the stream to a list using the Collect interface and the Collectors class.
  • Now convert the list to an array using the toArray() method.

Example

Live Demo

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class J8StreamToArray {
   public static void main(String args[]) {
      String[] myArray = { "JavaFX", "OpenCV", "WebGL", "HBase" };
      Stream<String> stream = Stream.of(myArray);
      List<String> list = stream.collect(Collectors.toList());
      String[] str = list.toArray(new String[0]);
      System.out.println(Arrays.toString(str));
   }
}

Output

[JavaFX, OpenCV, WebGL, HBase]
raja
Published on 08-Jan-2018 17:27:15
Advertisements