Java Stream toArray()

In this guide, you will learn about the Stream toArray() method in Java programming and how to use it with an example.

1. Stream toArray() Method Overview

Definition:

The Stream.toArray() method is a terminal operation used to obtain an array containing the elements of the stream.

Syntax:

Object[] toArray()

<A> A[] toArray(IntFunction<A[]> generator)

Parameters:

- generator: a function that produces a new array of the desired type and the provided length.

Key Points:

- It is a terminal operation, which means it ends the stream pipeline.

- The toArray() method comes in two variants:

1. One that produces an Object[].

2. Another that produces an array of a type determined by the provided generator function.

- If the stream is infinite, a java.lang.OutOfMemoryError may be thrown when trying to allocate an array of infinite length.

- The generator function gives more control over the runtime type of the output array.

2. Stream toArray() Method Example

import java.util.stream.Stream;

public class StreamToArrayExample {
    public static void main(String[] args) {
        Stream<String> fruitStream = Stream.of("Apple", "Banana", "Cherry", "Date", "Elderberry");

        // Convert the stream into an array of strings
        String[] fruitArray = fruitStream.toArray(String[]::new);

        // Print the array
        for (String fruit : fruitArray) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Cherry
Date
Elderberry

Explanation:

In the provided example: We have a stream of fruit names. Using toArray(), we convert this stream into an array of strings. The String[]::new is a constructor reference used as the generator function to produce the output array of the desired type. We then iterate through the array and print each fruit.

Comments