Android filter for ararians with a hamcrest jar

I have an android project that has its own list of arrays of objects, now I want to filter this list of arrays. But always I get zero (the size of the new list of arrays).

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 am I getting zero, please help.

0
source share
1 answer

The matcher.matches(item) operator in the filter method always returns false because you have string mappings ( Matchers.containsString ), but item is of type Products (it is assumed that productList contains elements of type Products ).

Matchers.containsString returns a match that inherits from the TypeSafeMatcher form and verifies that the matched value is of a compatible type. Therefore, it expects a String , but receives a Products object.

I see two options:

  • Change matcher.matches(item) to matcher.matches(item.getText()) where getText retrieves the corresponding string to match (you need to configure the <T><T extends Products> generators).
  • Create 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 name it like this:

     filter(new ProductsTextMatcher( Matchers.anyOf(Matchers.containsString(searchText), Matchers.containsString(searchText.toUpperCase()))), productList); 
0
source

Source: https://habr.com/ru/post/925005/


All Articles