Android arraylist filter with hamcrest jar

为君一笑 提交于 2019-12-12 01:36:05

问题


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) to matcher.matches(item.getText()) where getText extracts the relevant string to match (you have to adjust the generics <T> -> <T extends Products>).
  • Create a FeatureMatcher

    public 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!