Design for collections upgrades

Brian Goetz brian.goetz at oracle.com
Tue Mar 8 12:27:36 PST 2011


>       List<String>   things = ...
>       Collection<String>   fooAbles = things.filter(#Thing.isFoo); // ooh, pretty
>
> Not that pretty because filter have to create a new collection and
> there is no way to do that apart hard coding a new ArrayList somewhere.
>
> It's better in my opinion to have a filterTo that takes a collection
> as argument.
>
> Collection<String>   fooAbles = things.filterTo(#Thing.isFoo, new HashSet<>());

This works just fine when there's one operation in the pipeline, but 
starts to get clunky when the pipeline has multiple steps and you are 
explicitly specifying the "new ArrayList<>()" a bunch of times.

On the other hand, this works much better in the serial/lazy case, since 
the only place you need to choose a collection type is (typically) at 
the end of the pipeline:

   fooableWeights = foos.toStream()
                        .filter(#Thing.isFoo)
                        .map(#Thing.getWeight)
                        .toCollection(new ArrayList<>());

and we should definitely do this for the stream case.



More information about the lambda-dev mailing list