Search code examples
javasearcharraysrulespredicates

Predicate Searching in Java


Not quite sure how to word this question. I am wondering if there is a method to check certain parts of a custom java class to see if it matches a certain criteria. Such as this

public Name(String forename, String middlename, String surname)

And then when an array of instances of that class are created say,

Name[] applicants = new Name[4];

applicants[0] = new Name("john","bob", "rush");
applicants[1] = new Name("joe","bob", "rushden");
applicants[2] = new Name("jack","bob", "rushden");
applicants[3] = new Name("jake","bob", "rushden");

Is it possible to do a search over the instances of the class for person with

midddlename.equals("bob") && surname.equals("rush")

I am not really looking for a solution that is if(surname.equals("bob")) then else,etc

But more a in-built java class that allows for rapid searching over the array. the speed of this is very important.


Solution

  • There isn't built in support, but Apache Collections and Google Collections both provide Predicate support over collections.

    You may find this question and its answers helpful. Same with this developer.com article.

    e.g. Using Google Collections:

    final Predicate<name> bobRushPredicate = new Predicate<name>() {
       public boolean apply(name n) {
          return "bob".equals(n.getMiddlename()) && "rush".equal(n.getSurname());
       }
    }
    
    final List<name> results = Iterables.filter(applicants, bobRushPredicate));