I want to use Lambdaj and hamcrest matchers to simply check if sample string contains at least one of the list's item.
private static List<String> FIELDS=Arrays.asList("one","two","three","four");
String myString="This string may contain 'one' word or 'two' word";
boolean stringContainsItem=filter(Matchers.containsString(myString),FIELDS).isEmpty();
but the matcher is incorrect. I need in that place some inverted Matcher, which check if myString contains lists's item.
You can write your own matcher:
private static List<String> FIELDS=Arrays.asList("one","two","three","four");
String myString="This string may contain 'one' word or 'two' word";
boolean stringDoesNotContainItem=filter(createIsInStringMatcher(myString),FIELDS).isEmpty();
with:
private TypeSafeMatcher<String> createIsInStringMatcher(final String string) {
return new TypeSafeMatcher<String>() {
@Override
public void describeTo(Description description) {
}
@Override
protected boolean matchesSafely(String item) {
return string.indexOf(item) >= 0;
}
};
}
EDIT: There is also another Lambdaj method exists
which allows to write this in a more compact way:
List<String> FIELDS = Arrays.asList("one", "two", "three", "four");
String myString = "This string may contain 'one' word or 'two' word";
boolean stringContainsItem = Lambda.exists(FIELDS, createIsInStringMatcher(myString));