Using lambdaj with String.matches method

How to filter Collection<String>

using lambdaj and String.matches method.
I am new to lambda and feel stupid as the examples given are more complex than this.

+3


source to share


3 answers


This works, but I'm not happy with the fact that it takes a lot of code to replace a simple loop. I prefer to "filter" over "select" because it makes the code simpler and easier to read I think.



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

      

+1


source


If this could be done with a construct having(on(...))

, the call might look like this:

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

      



But unfortunately this is not possible since the class String

is final and therefore on(String.class)

cannot create the proxy required with having

.

Although hamcrest doesn't bring regex , you don't need to write your own. The web offers several implementations. I would like to see a helper like this in a ready-to-use public library that I could just include as a dependency instead of copying the source code.

+2


source


If you want to filter the collection, you can do as follows:

@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


source







All Articles