I'm looking for the answer for a question: how method .toArray(IntFunction<A[]> generator) knows the size of new Array.
Actually I know how to use this method to create new Array that contains all of stream
elements (e.g. String[]::new, Size -> new String[Size]
), but in the original java code we can see that the IntFunction<A[]>
generator applies given function to int argument. And there is my question HOW this function gets the number of elements of the stream.
I've been reading the source code of this classes for 3 hours, but I did not find the answer.
the answer to your question is stated in java docs.
toArray
uses the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.The generator function takes an integer, which is the size of the desired array and produces an array of the desired size.