Here is example of Java 8 convert Stream to Array like using ::new operator and IntFunction arguments. Stream contains toArray function using that we can convert Stream to Array.

Example 1: Convert Stream to Array using ::new

toArray return containing the elements of Array. toArray() return Array of Object while toArray(Employee[]::new) return array of Employee its describe as bellow:

java.util.List<Employee> employeeList = new ArrayList<>();
        employeeList.add(new Employee(1, "Jone"));
        employeeList.add(new Employee(2, "Shone"));

        Employee[] employeesArray =  employeeList.stream().toArray(Employee[]::new);   // its will create Array of Employee
                                                            
       // if you write employeeList.stream().toArray(); than it will create Array of Object                             

Example 2: Convert Stream to Array using IntFunction

Here is another version of toArray function of Stream class, Here we passed predefined size of array.

java.util.List<Employee> employeeList = new ArrayList<>();
        employeeList.add(new Employee(1, "Jone"));
        employeeList.add(new Employee(2, "Shone"));

Employee[] employeesArray = employeeList.stream().toArray(site->new Employee[site]);  // here wee are password fix length Employee Array

References:

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *