[英]Guava Predicate Failing To Filter Collection
我有以下使用謂詞來過濾集合的方法,將所有在propertyName不在給定值列表中的成員扔掉。 它使用Common-BeanUtils從對象中提取一個值,並且該值必須是String:
public static <T> void filterListByStringPropertyWithAllowableValues(List<T> listToFilter,
final String propertyName,
final List<String> allowedValues) {
Predicate<T> allowedValuesPredicate = new Predicate<T>() {
@Override
public boolean apply(T arg0) {
String value;
boolean result = false;
try {
value = BeanUtils.getProperty(arg0, propertyName);
System.out.println(value);
result = allowedValues.contains(value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return result;
}
};
Iterables.filter(listToFilter, allowedValuesPredicate);
}
不幸的是,我的測試完全失敗了。
@Test
public void testfilterListByStringPropertyWithAllowableValues() throws Exception {
TestClass item1 = new TestClass("value1","whatever1");
TestClass item2 = new TestClass("value2","whatever2");
TestClass item3 = new TestClass("value3","whatever3");
List<TestClass> initialList = Lists.newArrayList(item1, item2, item3);
MyCollectionUtils.filterListByStringPropertyWithAllowableValues(initialList, "importantField",
Lists.newArrayList("value1","value2"), 3);
assertTrue("Collection size should be 2. Actual: " + initialList.size(), initialList.size() == 2);
}
我在這里犯了一個非常愚蠢的錯誤嗎?
更新:工作代碼如下。
public static <T> List<T> filterListByStringPropertyWithAllowableValues(List<T> listToFilter,
final String propertyName,
final Set<String> allowedValues) {
Predicate<T> allowedValuesPredicate = new Predicate<T>() {
@Override
public boolean apply(T arg0) {
String value;
boolean result = false;
try {
value = BeanUtils.getProperty(arg0, propertyName);
System.out.println(value);
result = allowedValues.contains(value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return result;
}
};
return Lists.newArrayList(Iterables.filter(listToFilter, allowedValuesPredicate));
}
是的,您犯了一個非常愚蠢的錯誤;-)
您沒有返回過濾列表。 filter()
不會修改給定列表。 它返回一個過濾的Iterable。
另外,allowedValues應該是HashSet而不是List。 那將使您的過濾器更有效。 HashSet.contains()
在恆定時間內運行,而List.contains()
是O(n)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.