Converting Array to Stream

In this post under Java Collections, I will show with example how to convert an existing array to Stream.

For this purpose, Java provides static method named “stream” in Arrays class.

This method takes an array as an input and convert it into a stream.

Below is the complete main code for your reference

Main code

package core.collection;

import java.util.Arrays;
import java.util.stream.IntStream;

public class ConvertArrayToStream {
    public static void main(String[] args) {
        int[] intInputArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
        IntStream outputStream = Arrays.stream(intInputArray);
        outputStream.forEach(System.out::println);
    }
}

In the above code, I create an array of type integer and populate it.

Then I call “Arrays” class static method “stream” and passing the array as an argument.

This method will convert the passed in array as stream and it is assigned to variable “outputStream” of type “IntStream”

In this way we can convert an array to a stream.

Leave a comment