Question

Best explained with code I think, this is just a simple example:

public class MyPOJO {

    public String name;
    public int age;

    public MyPOJO(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class MyProcessor {

    public List<MyPOJO> process(List<MyPOJO> mypojos) {
        List<MyPOJO> temp = new ArrayList<MyPOJO>; 
        for (int i=0; i <moypojos.size(); i++) {
            if (filterOne(mypojos[i])) continue;
            if (filterTwo(mypojos[i])) continue;
            if (filterThree(mypojos[i])) continue;
            temp.add(mypojos[i];
        }
    }

    public boolean filterOne(MyPOJO mypojo) {
        // in practice filters aren't so basic
        return (mypojo.age < 21);
    }
    // assume implementations for the other filter methods
}

Yikes that's ugly. Basically I have a collection and I'd like to pass it through a sieve of sorts to only continue processing the objects that meet a certain criteria. My guess is there is a better pattern for this than a bunch of methods that return booleans.

Was it helpful?

Solution

You can have list of IFilters.

like so

boolean filtersResult = false;
for (IFilter filter : filters) {
    filterResult = filter.process(mypojos[i])

    if (filterResult)
        break;
}

OTHER TIPS

You may want to implement your filters such that they take a collection, and return a filtered collection:

public interface IFilter<E> {
  public Collection<E> filter(Collection<E> input);
}

This way you can chain together filters very trivially. The downside is that for large collections it is slower and takes more space; but the code is a lot more readable.

Why not use Bean-Query? it can make your code readable.

List<MyPOJO> result=selectBean(MyPOJO.class).where(
                                                not(
                                                  anyOf(
                                                      value("aga",lessThan(21)),
                                                      value("age",greaterThan(50))
                                                  )
                                                )
                                            .executeFrom(myPojos).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top