使用带有谓词的org.apache.commons.collections4.CollectionUtils的find方法
我使用的是org.apache.commons.collections.CollectionUtils,对于这个版本,使用find方法如下:使用带有谓词的org.apache.commons.collections4.CollectionUtils的find方法,collections,apache-commons,Collections,Apache Commons,我使用的是org.apache.commons.collections.CollectionUtils,对于这个版本,使用find方法如下: BeanPropertyValueEqualsPredicate objIdEqualsPredicate = new BeanPropertyValueEqualsPredicate("objId", objId); myObj = (MyClass) CollectionUtils.find(myObjSet, objIdEqualsPredicate
BeanPropertyValueEqualsPredicate objIdEqualsPredicate = new BeanPropertyValueEqualsPredicate("objId", objId);
myObj = (MyClass) CollectionUtils.find(myObjSet, objIdEqualsPredicate);
但是对于org.apache.commons.collections4.CollectionUtils,我不知道如何使它工作。
以下是我现在所做的,但如果有明确的方法,我将很高兴了解:
Predicate<MyClass> objIdEqualsPredicate = new Predicate<MyClass>() {
@Override
public boolean evaluate(MyClass obj) {
return obj.getObjId().equals(objId);
}
};
myObj = CollectionUtils.find(myObjSet, objIdEqualsPredicate);
是否有一种方法可以根据对象字段的值过滤某些对象。如果可能的话,我不想为此使用匿名类
谢谢。由于普通Beanutil仍将commons集合作为依赖项,因此必须实现谓词接口 例如,您可以获取BeanPropertyValueEqualsPredicate的源代码并对其进行重构,以便您的版本实现org.apache.commons.collections4.Predicate接口 或者你写你自己的版本。我不希望使用匿名内部类,因为可以为谓词编写单元测试并重用它 快速示例不安全
@Test
public class CollectionsTest {
@Test
void test() {
Collection<Bean> col = new ArrayList<>();
col.add(new Bean("Foo"));
col.add(new Bean("Bar"));
Predicate<Bean> p = new FooPredicate("Bar");
Bean find = CollectionUtils.find(col, p);
Assert.assertNotNull(find);
Assert.assertEquals(find.getFoo(), "Bar");
}
private static final class FooPredicate implements Predicate<CollectionsTest.Bean> {
private String fieldValue;
public FooPredicate(final String fieldValue) {
super();
this.fieldValue = fieldValue;
}
@Override
public boolean evaluate(final Bean object) {
// return true for a match - false otherwise
return object.getFoo().equals(fieldValue);
}
}
public static class Bean {
private final String foo;
Bean(final String foo) {
super();
this.foo = foo;
}
public String getFoo() {
return foo;
}
}
}
你试过什么?CollectionUtils仍然有一个find方法。让我们看看你已经试过了什么。还有,不要害怕匿名内部类,这就是它们存在的目的。@skaffman我已经添加了关于新类的详细信息。