How to Convert a Java 8 Stream to an Array?


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]

Updated on: 19-Dec-2019

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements