Stream to Array

Java-Stream to Array

Stream to Array

If you want to get the stream elements to an array, use the toArray( ) method. The toArray( ) method of Stream is used to get an array of the stream elements. This method has two forms. First:

Stream to Array

Since it is not possible to create a generic array at runtime, the expression stream.toArray() returns an Object[] array. The toArray() has another form this form is used to get correct type array. If you want an array of the correct type, pass in the array constructor.

Stream to Array


Program

Stream to Array
Program Source

import java.util.stream.Stream;

public class Javaapp {
    
    public static void main(String[] args) {

        Integer inary1[] = {10, 20, 30, 40, 50, 60};
        Stream<Integer> istm1 = Stream.of(inary1);
        Object objary[] = istm1.toArray();
        
        istm1 = Stream.of(inary1);
        Integer inary2[] = istm1.toArray(Integer[]::new);
        System.out.print("inary2--> ");
        for(Integer i:inary2){
            System.out.print(i+",");
        }
    }
}

Leave a Comment