Iterators.filter and remove

Brian Goetz brian.goetz at oracle.com
Tue May 22 07:27:10 PDT 2012


> It is not possible to remove an element from a collection while iterating
> with the iterator from java.util.Iterators.filter().

That's correct.

> 
> For some time now I've had a class in my personal toolkit called Filterable
> which is a filtered Iterable, and which allows remove when possible. It
> isn't likely to be at all common to remove items while iterating over a
> filtered collection, but there's no reason not to pass the remove call back
> to the upstream source, if possible.

Except for the many good reasons not to :)  

Stream operations are intended to be purely functional; if you want to mutate the underlying collection, there will be other methods added, such as Collections.removeIf(Predicate).  Of course, we can't prevent sneaky concurrent modification, but we don't have to enscourage it.  

One of the nice features of this facility is the ability to do parallel operations on existing non-thread-safe collections -- you can take an ordinary ArrayList and do a parallel reduce on it.  That's really nice!  The price for this is non-interference -- you can't mutate the collection while you're operating on it.  In reality, this restriction is not hard to comply with; non-thread-safe collections are generally thread-confined, so as long as the owning thread isn't doing anything else while a parallel op is going on, and the framework is correctly written (that's our job), this is safe.  Of course, we can't prevent people from doing dumb things like mutating the collection from a Predicate or Mapper, but as I said, we don't have to encourage it.  


> I quite prefer accept to eval, for what it's worth.

Yes, all the names are provisional.  There's a strong argument for ensuring that no two standard SAM types have the same method name, though.  


More information about the lambda-dev mailing list