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)) select.add(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!
2 comments:
Sam Newman has released similar code as hamcrest-collections. It's linked from the Uses of Hamcrest page on the hamcrest project site.
The Scrabble geek in me noticed quickly that "Hamcrest" is an anagram of "matchers"....8^)
Post a Comment