Loose ends: Collection.toArray(IntFunction<A[]> generator)
Paul Sandoz
paul.sandoz at oracle.com
Thu May 30 02:18:43 PDT 2013
A while ago there was some lively discussion on toArray and we finally settled on the following method in Stream:
<A> A[] toArray(IntFunction<A[]> generator);
Due to "noise" of other stuff i think we forgot to discuss whether it is valuable to add a similar default method to Collection (as recently suggested by Peter Levart on the lambda-dev list which motivated this email).
The functionality can already be achieved with:
c.stream().toArray(String[]::new);
but is not likely to be as efficient as the existing concrete Collection.toArray implementations (e.g. see ArrayList.toArray)
This is also the way to produce an array in parallel:
c.parallelStream().toArray(String[]::new);
where efficiencies can be obtained if the collection is large enough.
But we could also add to Collection:
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(size()));
}
c.toArray(String[]::new);
Seems like a reasonable thing to do. The sequentially efficiency is retained without the "stink" of using the other toArray method accepting an array instance (of or not of the right length).
Paul.
More information about the lambda-libs-spec-experts
mailing list