Java 8: Convert Stream to Array


To convert a Java 8 Stream to an Array, we can make use of the toArray() method on the Stream object.

Let's take a look at it with a few examples.

Example 1:
package org.code2care.java.examples;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8StreamToArrayExample {

    public static void main(String[] args) {

        List<Integer> numbersList = new ArrayList<>();
        numbersList.add(10);
        numbersList.add(20);
        numbersList.add(30);
        numbersList.add(40);
        numbersList.add(50);

        int[] intArray = numbersList.stream()
                .mapToInt(Integer::intValue)
                .toArray();

        System.out.println(Arrays.toString(intArray));
    }
}

Example 2:
package org.code2care.java.examples;

public class Employee {

    private String empName;
    private int empInt;

    public Employee(String empName, int empInt) {
        this.empName = empName;
        this.empInt = empInt;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpInt() {
        return empInt;
    }

    public void setEmpInt(int empInt) {
        this.empInt = empInt;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empName='" + empName + '\'' +
                ", empInt=" + empInt +
                '}';
    }
}
package org.code2care.java.examples;

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

public class StreamToArrayExample2 {
    public static void main(String[] args) {
        List<Employee> employeeList = Arrays.asList(
                new Employee("Mike", 101),
                new Employee("Sam", 202),
                new Employee("Andrew", 303)
        );

        Stream<Employee> stream = employeeList.stream();
        Employee[] array = stream.toArray(Employee[]::new);

        System.out.println(Arrays.toString(array));
    }
}
Output:

[Employee{empName='Mike', empInt=101}, Employee{empName='Sam', empInt=202}, Employee{empName='Andrew', empInt=303}]

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap