【问题标题】:Using lambdaj with String.matches method将 lambdaj 与 String.matches 方法一起使用
【发布时间】:2012-04-06 13:38:15
【问题描述】:

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

【问题讨论】:

    标签: java hamcrest lambdaj


    【解决方案1】:

    如果可以使用having(on(...)) 构造来实现,调用可能如下所示:

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

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

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

    【讨论】:

      【解决方案2】:

      如果你想过滤一个集合,你可以按如下所述进行:

      @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());
      }
      

      【讨论】:

      • 谢谢...我想我仍然不相信 1. 语法是如此冗长 2. 我必须编写自己的匹配器来启动,因为似乎没有正则表达式匹配器hamcrest。
      【解决方案3】:

      这行得通,但我不高兴需要这么多代码来替换一个简单的 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);
        }
      

      【讨论】:

      • 嗯,它需要那么多代码一次。我在我的单元测试库中添加了一个正则表达式匹配器,所以我不必再次编写它。如果我曾经在生产代码中使用匹配器,我只会将正则表达式匹配器移动到适当的库中。正如我在回答中提到的,我希望在现成的公共图书馆中看到这个匹配器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多