1

我想使用 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();

但匹配器不正确。我在那个地方需要一些倒置的匹配器,它检查 myString 是否包含列表的项目。

4

1 回答 1

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));
于 2014-10-21T17:32:02.400 回答