Course contentsShow
← Java
Lesson 1499 of 2,87033. Streams API: Terminal OperationsFree lesson

Primitive Streams and toArray()

Learn that IntStream.toArray() returns int[] directly without needing a generator function.

Primitive Streams and toArray()

You'll learn: How primitive streams like IntStream provide a simpler toArray() method that returns a primitive array directly, without requiring a generator function.

The Special Case for Primitive Streams

When you worked with regular Stream<T> objects, you learned that toArray() returns Object[] by default, and you need to supply an IntFunction<A[]> generator to get a typed array like String[].

Primitive streams are different. Since IntStream, LongStream, and DoubleStream work with primitive types, they already know exactly what array type to create. There's no ambiguity, so no generator function is needed.

How It Works

When you call toArray() on an IntStream, it returns int[] directly:

IntStream numbers = IntStream.of(1, 2, 3, 4, 5);
int[] array = numbers.toArray();  // Returns int[] directly

No lambda, no method reference, no generator function needed. The same applies to the other primitive streams:

  • LongStream.toArray() returns long[]
  • DoubleStream.toArray() returns double[]

Why This Simplification Matters

This convenience exists because primitive arrays have no type erasure issues. The stream knows it contains int values, so it can only produce an int[]. There's no need to tell it what type you want—unlike with generic streams where Stream<Integer> could theoretically become Integer[], Object[], or Number[].

Key Takeaway: Primitive streams (IntStream, LongStream, DoubleStream) have a simplified toArray() method that returns the corresponding primitive array type (int[], long[], double[]) directly, without needing a generator function parameter.