Simple linear search
public interface Predicate
{
public boolean test(Object x);
}
Object findIf(Collection coll, Predicate test)
{
for(Iterator i = coll.iterator(); i.hasNext(); )
{
Object current = i.next();
if(test.test(current))
return current;
}
return null;
}
We can argue the toss about single exit points, but that's a reasonable implementation, yes?
Let's put that into Java.
Look ok. Everyone ok with the Comparator, and why I might use it instead of .equals?
[[ Comparators are used to specify object orderings. Returns 0 if objects are equal. By passing one in, we allow more or less arbitrary comparisons.]]
Comparators are useful if we want to search for equality - are there any objects the same as this one. However, we might want to search, as we did early, for objects matching some other conditions. In this kind of case a Predicate - a function object/functor/callable object - which defines some test and returns true/false. [[In C++, you'd implement this as an class defining operator()]]. Here, the Predicate is an interface defining a single method, test, which takes an object and returns a boolean. I'd submit that this second form is going to be more useful that the first. [[And it's a straightforward exercise to rewrite the first in terms of the second.]]
So, here's our simple search. Is it ok? Is it useful? Could it be more useful? I think so. We're passing in a Collection at the top. Do I really need to. Java has some pretty demanding ideas about what a Collection is.