You can combine apache commons-beanutils and commons-collections.
The short answer
Predicate selectPredicate = new BeanPropertyValueEqualsPredicate(
"selected", Boolean.TRUE);
Collection selectedObjects = CollectionUtils.select(
Arrays.asList(objects), selectPredicate);
A Unit-Test example
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.junit.Assert;
import org.junit.Test;
public class ObjectSelectionTest {
@Test
public void objectSelection() {
MyObject obj1 = new MyObject();
MyObject obj2 = new MyObject();
obj2.setSelected(true);
MyObject obj3 = new MyObject();
MyObject[] objects = new MyObject[] { obj1, obj2, obj3 };
Predicate selectPredicate = new BeanPropertyValueEqualsPredicate(
"selected", Boolean.TRUE);
Collection selectedObjects = CollectionUtils.select(
Arrays.asList(objects), selectPredicate);
Assert.assertEquals(1, selectedObjects.size());
Object selected = selectedObjects.iterator().next();
Assert.assertSame(obj2, selected);
}
public static class MyObject {
private boolean selected;
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
}