Search code examples
javahamcrest

Hamcrest matcher for a sublist/partial match?


Say I have an actual List [1, 2, 3, 4] and I want to check if it contains the sub-list [2, 3] (i.e. order is also important). Is there an existing matcher that does this?

(There's a poorly-named hasItems method which only checks the actual list matches any one item in the expected list....)


Solution

  • Write your own if you can.

    see Writing custom matchers

    It should be something like:

     public class HasSublist<T> extends TypeSafeMatcher<T> {
    
         @Override
          public boolean matchesSafely(List<T> subList) {
            //Logic if sublist exist ...
            return true;
          }
    
          public static <T> Matcher<T> hasSubList(List<T> containsSublist) {
            return new HasSublist<T>(containsSublist);
          }
    }