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

Array Generator Function Syntax

Understand how the int parameter represents array size in the generator function you provide.

Array Generator Function Syntax

What you'll learn: How the integer parameter in your array generator function tells the Stream exactly what size array to create.

Understanding the Generator Function's Parameter

When you call toArray(IntFunction<A[]>), you provide a function that takes a single int parameter. This integer represents the exact number of elements the Stream needs to store—in other words, the required array size.

Think of it like ordering a custom box: the Stream counts all the items it needs to pack, then tells your generator function "I need a box that fits exactly 15 items." Your function's job is simply to create an array of that size.

The Syntax Explained

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

In this example:

  • size is the parameter name (you can name it anything: n, length, count, etc.)
  • The Stream internally calculates how many elements it has
  • It passes that count to your lambda as the size argument
  • Your lambda creates and returns a new array of exactly that size
  • The Stream fills it automatically

Why You Don't Specify the Size Yourself

You might wonder: "Can't I just write new String[100]?" You could, but you don't know ahead of time how many elements the Stream contains! The Stream has already processed all operations and knows the exact count—it just needs you to provide the constructor for the right type.

// Stream knows: "I have 7 elements"
// Your function receives: 7
// You return: new String[7]
String[] array = names.toArray(n -> new String[n]);

Key Takeaway: The int parameter in your generator function is the Stream's way of telling you exactly how large the result array needs to be—you simply use that number to construct the correctly-sized array.