How to Convert Stream to an Array

JavaJavaBeginner
Practice Now

Introduction

In Java, a stream is a sequence of elements on which we can perform operations in a functional approach. On the other hand, an array is an object that stores a similar type of element. In this lab, we will learn how to convert a stream to an array in Java.

Convert an Integer stream to an int Array

In this step, we will create a sequence of integers using the rangeClosed() method of IntStream and convert it to an array using the toArray() method.

import java.util.stream.IntStream;

public class StreamToArray {
    public static void main(String[] args){
        IntStream integerStream = IntStream.rangeClosed(1, 5);

        // convert the stream into an int array
        int[] arr = integerStream.toArray();

        // print each element of the array
        for(int e: arr) {
            System.out.println(e);
        }
    }
}

The output of the code will be as follows:

1
2
3
4
5

Convert a String Stream to a String Array

In this step, we will create a stream of string values from a list and convert it into an array using the toArray() method.

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

public class StreamToArray {
    public static void main(String[] args){
        Stream<String> stream = List.of("UK", "US", "BR").stream();

        // convert the string stream into a string array
        String[] strArray = stream.toArray(String[]::new);

        // print each element of the string array
        for(String str : strArray) {
            System.out.println(str);
        }

        // convert the string array into a stream again
        Stream<String> stringStream = Arrays.stream(strArray);

        // print each element of the stream
        stringStream.forEach(System.out::println);
    }
}

The output of the code will be as follows:

UK
US
BR

UK
US
BR

Summary

In this lab, we learned how to convert a stream to an array in Java. We used the toArray() method of the stream to convert it into an array. The syntax for this method is straightforward, and it returns an array of the specified type. We saw examples of converting integer and string streams into their respective arrays.

Other Java Tutorials you may like