Saturday, October 27, 2007

Hamcrest matchers

I missed this post from Joe Walnes a while ago on using Hamcrest matchers for more than testing.

I appreciate their DSL-like quality and clever mixture of literate class names, static factory methods and Java generics.

In his post Joe Walnes references Håkan Råberg's nice idea for filtering collections with Hamcrest matchers, but unfortunately that post links to no code, usage examples. select and reject are trivial to code:

public static <T> List<T> select(
        final Collection<T> c,
        final Matcher<T> matcher) {
    final List<T> select = new ArrayList<T>();

    for (final T t : c)
        if (matcher.matches(t))

    return select;

public static <T> List<T> reject(
        final Collection<T> c,
        final Matcher<T> matcher) {
    return select(c, not(matcher));

The statically-typed query API is not so trivial to toss off early in the morning. Hopefully Håkan Råberg will release code at some point.

UPDATE: Nat Pryce was kind enough to point to Hamcrest Collections, itself inspired by Håkan Råberg's post. Thanks, Nat!

Post a Comment