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

Using IntFunction<A[]> to Specify Array Type

Pass a constructor reference or lambda to toArray(String[]::new) for strongly-typed arrays.

Using IntFunction<A[]> to Specify Array Type

What you'll learn: How to get a strongly-typed array from a stream instead of the default Object[].

The Problem with Default toArray()

In the previous lesson, you learned that calling toArray() without arguments returns an Object[]. This forces you to cast the result, which is error-prone and defeats type safety:

Stream<String> stream = Stream.of("apple", "banana", "cherry");
Object[] objects = stream.toArray(); // Returns Object[]
String[] strings = (String[]) objects; // ClassCastException at runtime!

The Solution: Pass a Generator Function

The toArray() method has an overloaded version that accepts an IntFunction<A[]> parameter. This function receives the desired array size as an int and returns a new array of that size and the correct type.

The most common approach is to pass a constructor reference:

Stream<String> stream = Stream.of("apple", "banana", "cherry");
String[] strings = stream.toArray(String[]::new);
// Returns String[], not Object[]

Here, String[]::new is a constructor reference that creates a String array of the specified size. The Streams API calls this function with the exact count of elements, allocates the array, and fills it.

Alternative: Lambda Expression

You can also use a lambda if you prefer being explicit:

String[] strings = stream.toArray(size -> new String[size]);

Both approaches do the same thing—the constructor reference is just more concise.

Why This Matters

This technique preserves type information, eliminates casting, and catches type errors at compile time rather than runtime. It's the proper way to collect stream elements into a typed array.

Key Takeaway: Pass a constructor reference like String[]::new to toArray() to get a strongly-typed array instead of Object[], avoiding unsafe casts and runtime errors.