userimage

Finding all objects that have a given property inside a collection

Lets think that I have some complicated object, such as a Cat, which has many properties, such as age, favorite cat food, and so forth.

A bunch of Cats are stored in a Java Collection, and I need to find all the Cats that are aged 3, or those whose favorite cat food is Whiskas. Surely, I can write a custom method that finds those Cats with a specific property, but this gets cumbersome with many properties; is there some generic way of doing this?

userimage

You could write a method that takes an instance of an interface which defines a check(Cat) method, where that method can be implemented with whatever property-checking you want.

Better yet, make it generic:

public interface Checker<T> {

    public boolean check(T obj);

}

public class CatChecker implements Checker<Cat> {

    public boolean check(Cat cat) {

        return (cat.age == 3); // or whatever, implement your comparison here

    }

}

// put this in some class

public static <T> Collection<T> findAll(Collection<T> coll, Checker<T> chk) {

    LinkedList<T> l = new LinkedList<T>();

    for (T obj : coll) {

         if (chk.check(obj))

             l.add(obj);

    }

    return l;

}

Of course, like other people are saying, this is what relational databases were made for...

userimage
Moe

I have been using Google Collections (now called Guava) for this kind of problem. There is a class called Iterables that can take an interface called Predicate as a parameter of a method that is really helpful.

Cat theOne = Iterables.find(cats, new Predicate<Cat>() {
    public boolean apply(Cat arg) { return arg.age() == 3; }
});

Check it here!

Answer is