问题
I have an android project, which have an custom object array list, now I want to filter that array list. But always I get zero (size of new array list).
public static <T> List<T> filter(Matcher<?> matcher, Iterable<T> iterable) {
if (iterable == null)
return new LinkedList<T>();
else{
List<T> collected = new LinkedList<T>();
Iterator<T> iterator = iterable.iterator();
if (iterator == null)
return collected;
while (iterator.hasNext()) {
T item = iterator.next();
if (matcher.matches(item))
collected.add(item);
}
return collected;
}
}
ArrayList<Products> sortedArrayList = (ArrayList<Products>) filter(Matchers.anyOf(
Matchers.containsString(searchText),Matchers.containsString(searchText.toUpperCase())), productList);
Why I am getting zero, please help.
回答1:
The statement matcher.matches(item) in the filter method returns always false because you have string matchers (Matchers.containsString) but item is of type Products (assuming that productList contains items of type Products).
Matchers.containsString returns a matcher which inherits form TypeSafeMatcher and checks that the matched value has a compatible type. So it expects a String but get a Products object.
I see two options:
- Change
matcher.matches(item)tomatcher.matches(item.getText())wheregetTextextracts the relevant string to match (you have to adjust the generics<T>-><T extends Products>). Create a
FeatureMatcherpublic class ProductsTextMatcher extends FeatureMatcher<Products, String> { public ProductsTextMatcher(Matcher<? super String> subMatcher) { super(subMatcher, "", ""); } @Override protected String featureValueOf(Products actual) { return actual.getText(); } }and call it like so:
filter(new ProductsTextMatcher( Matchers.anyOf(Matchers.containsString(searchText), Matchers.containsString(searchText.toUpperCase()))), productList);
来源:https://stackoverflow.com/questions/35988831/android-arraylist-filter-with-hamcrest-jar