In a Java program, I have a list of beans that I want to filter based on a specific property.
For example, say I have a list of Person, a JavaBean, where Person has
Here is an example of using generics using guava, beanutils to filter any list using requested match
/**
* Filter List
*
* @param inputList
* @param requestMatch
* @param invokeMethod
* @return
*/
public static <T> Iterable<T> predicateFilterList(List<T> inputList, final String requestMatch,
final String invokeMethod) {
Predicate<T> filtered = new Predicate<T>() {
@Override
public boolean apply(T input) {
boolean ok = false;
try {
ok = BeanUtils.getProperty(input, invokeMethod).equalsIgnoreCase(requestMatch);
}
catch (Exception e) {
e.printStackTrace();
}
return ok;
}
};
return Iterables.filter(inputList, filtered);
}
Speaking as the developer of guava-reflection, I am sorry that I have abandoned this project at such an early stage (I have a day job and a wife & kids :-)). My vision was something like:
Iterable<Object> thingsWithNames =
Iterables.filter(someData,
// this is a Predicate, obviously
BeanProperties.hasBeanProperty("name", String.class));
The existing code is about 60% there, so if you are interested, contact me and perhaps we can get this finished together.
Do it the old-fashioned way, without Guava. (Speaking as a Guava developer.)
List<Person> filtered = Lists.newArrayList();
for(Person p : allPersons) {
if(acceptedNames.contains(p.getName())) {
filtered.add(p);
}
}
You can do this with Guava, but Java isn't Python, and trying to make it into Python is just going to perpetuate awkward and unreadable code. Guava's functional utilities should be used sparingly, and only when they provide a concrete and measurable benefit to either lines of code or performance.