将lambdaj与String.matches方法一起使用

时间:2012-04-06 13:38:15

标签: java hamcrest lambdaj

如何使用lambdaj和String.matches方法过滤Collection<String> 我是lambdaj的新手并且感到愚蠢,因为给出的例子比这更复杂。

3 个答案:

答案 0 :(得分:2)

如果可以使用having(on(...))构造进行,则调用可能如下所示:

select(collection, having( on(String.class).matches("f*") ))

但不幸的是,这是不可能的,因为String类是最终的,因此on(String.class)无法创建having匹配器所需的代理。

尽管hamcrest没有带来正则表达式匹配,但您不必编写自己的。网提供了几种实现方式。我希望在即用型公共库中看到这样的匹配器,我可以将其简单地包含为依赖项,而不必复制源代码。

答案 1 :(得分:1)

如果您想过滤收藏品,可以按照以下说明进行操作:

@Test
public void test() {
    Collection<String> collection =  new ArrayList<String>();
    collection.add("foo");
    collection.add("bar");
    collection.add("foo");

    List<String> filtered = select(collection, having(on(String.class), equalTo("foo")));
    assertEquals(2, filtered.size());
}

答案 2 :(得分:1)

这样可行,但我很高兴需要这么多代码来替换一个简单的for循环。 我更喜欢“过滤”而不是“选择”,因为它使代码更简单,更容易阅读。

  public Collection<String> search(String regex) {
    List<String> matches = filter(matches(regex), dictionary);
    return matches;
  }

  static class MatchesMatcher extends TypeSafeMatcher<String> {

    private String regex;

    MatchesMatcher(String regex) {
      this.regex = regex;
    }

    @Override
    public boolean matchesSafely(String string) {
      return string.matches(regex);
    }

    public void describeTo(Description description) {
      description.appendText("matches " + regex);
    }

  }

  @Factory
  public static Matcher<String> matches(String regex) {
    return new MatchesMatcher(regex);
  }