Working with immutable collections
Brian Goetz
brian.goetz at oracle.com
Mon Nov 19 08:06:30 PST 2012
I understand the use case.
The specific suggestion (add a new stream operation for this one use
case, that cannot help with others, and will invariably give birth to
cries for many more) would be a serious mistake.
What I think you want is a Builder that implements Destination,
therefore piggybacking on the mechanism that lets into work with any
Collection type (and more). Then it is entirely supported within the
library:
class MyCollectionBuilder<T> implements Stream.Destination {
void addAll(...)
T build() ...
}
and then you could say
stream.filter(...).blah(...)
.into(new MyCollectionBuilder(new ArrayList())).build();
On 11/19/2012 9:39 AM, Johan Haleby wrote:
> Hi,
>
> I'm sorry if this has been discussed before but here goes:
>
> Let's say I have an immutable list called "xList" that I want to filter and
> return the result as a new *immutable* list. I could do something like this:
>
> Collections.unmodifiableList(xList.filter(obj -> obj.something()).into(new
> ArrayList<X>())));
>
> How ever I think this is quite verbose and doesn't follow the fluent style
> of the API. What I would like to have is something a long these lines:
>
> xList.filter(obj -> obj.something()).intoImmutable(new ArrayList<X>()));
>
> "intoImmutable" could then do "Collections.unmodifiableList(..)" for me so
> I don't need to wrap all statements where I want to return an immutable
> collection.
>
> What are your thoughts on this?
>
> Regards,
> /Johan
>
More information about the lambda-dev
mailing list