I’m writing a small application which needs to perform a common task on a lot of different lists: Filtering objects by given criteria.
For example there’s an ArrayList of the class Foo which has the attributes int bar and boolean baz:
class Foo {
int bar;
boolean baz;
}
I want to retrieve a new list which contains only objects that match a given criteria (for example bar > 1) from that ArrayList. In other languages like Perl I’d simply use grep() to get all these Objects:
@where_bar_greater_one = grep { $_->{bar} > 1 } @list;
But it doesn’t seem to be that easy with Java. Right now I’ve emulated this behaviour with a static method that iterates over all elements with an anonymous inner class:
interface ListPredicate<T> {
boolean match(T item);
}
class ListUtil {
public static <T> List<T> grep(List<T> source, ListPredicate<T> predicate) {
ArrayList<T> results = new ArrayList<T>();
for(T item : source) {
if(predicate.match(item)) results.add(item);
}
return results;
}
}
ArrayList<Foo> found = new ArrayList<Foo>(ListUtil.grep(list, new ListPredicate<Foo>() {
@Override public boolean match(Foo item) {
return item.bar > 1 ? true : false;
}
}));
Compared to the small piece of Perl this code looks rather bloated and I’m wondering if I didn’t miss something. So this leaves me with two questions:
- Is there a shorter (and perhaps cleaner) way to do this without using any external libraries?
- Are there recommended open-source libraries which provide methods for such common higher-order functions (like
grep,foldLeft,reduceLeft,mapand so on…)?
You can use JFilter to query java collections.
Another option is to use Commons Collections with predicates (as explained here)
Good luck!