ArrayFactory SAM type / toArray

Sam Pullara sam at
Wed Sep 19 15:58:05 PDT 2012

I think that we should not only use this proposal but also make it
work for .into() so i can pass in a lambda that gets a size if it is

interface CollectionFactory<T extends Collection> {
  T create(int minSize);

Stream.into(CollectionFactory<T> factory)

stream.into(n -> new ArrayList(n))

I don't think I have ever NOT created mine to be the right size and
type with the current API.


On Wed, Sep 19, 2012 at 3:33 PM, Joshua Bloch <josh at> wrote:
> Brian,
> On Wed, Sep 19, 2012 at 3:13 PM, Brian Goetz <brian.goetz at> wrote:
>>> I don't find these arguments convincing.  There's no race (any more than
>>> there is for any bulk operation) as the allocation is done by the object
>>> itself.  The allocation stuff is pretty much a red herring: most users
>>> don't preallocate the array. So it seems to me that using factories here
>>> might amount to needless complexity and inconsistency.
>> I agree with you that most users don't pre-allocate the array.  Which
>> makes the existing form of toArray even more unfortunate!  Because then the
>> allocation always involves multiple reflective calls.  (Some of which are
>> sometimes optimized by some VMs in some conditions, but none of which are
>> always optimized by all VMs in all conditions.)  So the performance will
>> always be worse in the toArray(T[]) formulation.
> Performance is typically irrelevant.  In the rare cases where it isn't, you
> preallocate.  Warping API for performance is generally a bad idea.
>> We're creating a new API here.
> Yeah, I haven't exactly been keeping up, so I don't know the context. That
> said, the current toArray APIs are pretty good.  I've never heard anyone
> complain about them.
>> Here are what the client callsites might look like in various cases:
>>  // status quo
>>  Foo[] foos = ...toArray(new Foo[0]);            // ugh reflection
> I agree that the above is a bit nasty. I think some syntactic sugar, perhaps
> coupled with a cache of commonly used 0-length arrays might be a good idea.
>     Josh

More information about the lambda-libs-spec-observers mailing list