I have list List
where Custom
is like
class Custom{
public int id;
public String name;
}
How to
If you are going to filter by name in several places, and particularly if you are going to chain that filter with others determined at runtime, Google Guava predicates may help you:
public static Predicate nameIs(final String name) {
return new Predicate() {
@Override public boolean apply(Custom t) {
return t.name.equals(name);
}
};
}
Once you've coded that predicate, filtering and counting will take only one line of code.
int size = Collections2.filter(customList, nameIs("Tom")).size();
As you can see, the verbose construction of a predicate (functional style) will not always be more readable, faster or save you lines of code compared with loops (imperative style). Actually, Guava documentation explicitly states that imperative style should be used by default. But predicates are a nice tool to have anyway.