我想使用Lambdaj和hamcrest匹配器来检查样本字符串是否至少包含一个列表项。
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();
但匹配器不正确。 我需要在那个地方有一些倒置的Matcher,它检查myString是否包含列表的项目。
答案 0 :(得分:1)
您可以编写自己的匹配器:
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();
使用:
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;
}
};
}
编辑:还有另一种Lambdaj方法exists
允许以更紧凑的方式编写它:
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));