Remove
interface Collection
{
...
boolean remove(Object o);
...
}
void removeIf(Iterator iter, Predicate test)
{
while(iter.hasNext())
{
Object o = iter.next();
if(test.test(obj))
iter.remove();
}
}
Back near the beginning of this talk, I said that I didn't think remove should be part of the iterator interface. But it is, so we've got two choices - pretend it isn't there and ignore it, or try and get some use out of it.
The Collection interface has remove, which is pretty basic. If we have an iterator that supports remove, then we can write a method to remove arbitrary objects. Here's a removeIf that takes out all the elements matching a Predicate. We could easily just remove the first match if we wanted, or we could return a count of elements removed.
Notice that if we start to use method like findIf or removeIf, then we stop writing our own for loops. In a curious kind of way, we sort of/kind of moving toward the kind of thing we saw in Ruby code back at start. However, the crucial difference here is that we control the iterator. In the Ruby example, we handed over our block and said "get on with it". Here, the iteration is under our control.
I'm not expecting you all to rush out and think of all the possible scenarios you can, and write a million little library iterators and methods, even if they are all very short and straightforward. What I'm suggesting is that you be aware of the recurring patterns in your own code, and consider lifting them out into a library. Built as you go.
Let's go back to findIf.