'Why does the Java Stream API omit the 'toArray(T[] a)' overload for writing to an existing array?
While the Collection API provides three overloads of toArray
Object[] toArray()T[] toArray(IntFunction<T[]> generator)T[] toArray(T[] a)
the Stream API only provides the first two of those. That is, it does not provide a way to use an existing array as the return value of the stream-to-array conversion.
--> What is the reason for the omission of toArray(T[] a) in Stream ?
I imagine the main reason is the functional spirit of streams, which would make a side effect like writing to an existing array undesired. Is this correct ? Are there other reasons that would make the other two versions preferrable ? Maybe there are even reasons that make them also preferrable on a Collection ?
Solution 1:[1]
The common pattern (at least according to my observations) for the use of Collection.toArray(T[]) was this one:
var array = list.toArray( new T[0] );
meaning that an empty array with size 0 was provided.
Calling toArray() with an existing array allowed to return an array of the proper type, in opposite to an array of Object. There was no other way to give the type of the desired return type into the method than via a 'sample'. You can think about like toArray( Class<T> elementType ) instead, but that does not work proper if T is a parameterised type as well.
When Lambda were introduced, the variant with the IntFunction<T[]> replaced the variant with the existing array in its functionality, therefore it was omitted for Stream. I expect that Collection.toArray(T[]) will be deprecated soon, and will be removed with one of the upcoming LTS versions – not with the next, or that one after the next, of course!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pshemo |
