Simple linear search


Object find(Collection coll, Object target, Comparator comparator)
{
  for(Iterator i = coll.iterator(); i.hasNext(); )
  {
    Object current = i.next();
    if(comparator.compare(current, target) == 0)
      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 (eg age < 30), or it might be difficult to construct the exemplar (complex object, stateful, db-backed, etc). 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.]]