Why no return a collection when possible?

Brian Goetz brian.goetz at oracle.com
Sat Aug 4 15:24:00 PDT 2012


See the section on laziness in: http://cr.openjdk.java.net/~briangoetz/lambda/collections-overview.html

> There are many cases in which the entry point of a pilpeline is a collection
> and its size has not changed at the other end (no filters invoked). 
> In this case it would be good to get a Collection. Currently I doing this by
> hand at the end of each pipeline using something like this:
> 
> public static <T> Collection<T> newCollection(final Iterable<T> iterable,
> final int size) {
>     return new AbstractCollection<T>() {
>           public Iterator<T> iterator() {
>                return iterable.iterator();
>            }
>            public int size() {
>                return size;
>            }
>      };
> }
> 
> The point is to preserve compatibility with the existing code, refractoring
> collections to Iterables would be a major task.

No, this is incorrect.  On the source side, Collection is-a Iterable.  So consuming a collection is no problem.  On the destination side, there's the into() method.  If you want a Collection, use that.  If you don't need a Collection, don't pay to instantiate one and copy all the elements when you don't need to.  

In neither case is there a "major" refactoring of any kind.



More information about the lambda-dev mailing list