Program to convert Stream to an Array in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our stream −

Stream<Integer> stream = Stream.of(50, 100, 200, 400, 800, 1000, 2000);

Now, convert stream to an array using toArray() −

Object[] objArr = stream.toArray(Object[] ::new);

Following is the program to convert Stream to an Array in Java −

Example

import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
public class Demo {
   public static void main(String args[]) {
      Stream<Integer> stream = Stream.of(50, 100, 200, 400, 800, 1000, 2000);
      Object[] objArr = stream.toArray(Object[] ::new);
      System.out.println("Array = "+ Arrays.toString(objArr));
   }
}

Output

Array = [50, 100, 200, 400, 800, 1000, 2000]
raja
Published on 24-Sep-2019 10:38:06
Advertisements