Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Convert a stream to a typed array with Stream.toArray(IntFunction)

Collect stream elements into an array of a chosen type, such as `String[]`, by supplying a function that creates an array of the requested length.

Version: Java SE 21

Syntax

<A> A[] toArray(java.util.function.IntFunction<A[]> generator)

In Java SE 21, Stream.toArray(IntFunction) on java.util.stream.Stream<T> collects the pipeline's output elements into an A[]. It is a terminal operation: you cannot reuse the same stream afterward. If the stream has an encounter order, the array preserves it.

The java.util.function.IntFunction<A[]> generator takes an int length and returns a new array of that length. Here, String[]::new means the same thing as length -> new String[length]. The stream supplies the size; do not assume it calls the generator only once. It may need extra arrays when splitting the work into parts or resizing.

The no-argument toArray() returns an Object[] whose runtime component type is Object, even for a Stream<String>. In the generator overload, A is the array's component type, independent of the stream's element type T. The method does not convert elements: it throws ArrayStoreException if an element cannot be stored in the array because of its runtime component type.

Examples

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

public class StreamToArrayExample {
    public static void main(String[] args) {
        String[] names = Stream.of("Ada", "Bo", "Clara")
                .filter(name -> name.length() >= 3)
                .toArray(String[]::new);

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

Result

[Ada, Clara]

`filter` excludes `Bo` because the name is shorter than 3 characters. `String[]::new` lets you assign the result to `String[]` without a cast, and `Arrays.toString` displays `[Ada, Clara]`.

Related lessons

  • Java · Lesson 63 · Basic · Version: 2

Sources