Today I had a glance at commons collections. I’m convinced, that the more mature parts of the commons are what sun forgot about. If you know and use them you’ve definitely got a competive advantage.
But now for the code:
public class CollectionsDemo {
public static void main(String[] args) {
List list= Arrays.asList(new String[]{"Hund","Katze","Huhn"});
List hList = (List) CollectionUtils.select(list,new Predicate() {
public boolean evaluate(Object object) {
return ((String)object).startsWith("H");
}
});
System.out.println(hList);
List upperList=(List)CollectionUtils.collect(list, new Transformer() {
public Object transform(Object object) {
return ((String)object).toUpperCase();
}
});
System.out.println(upperList);
}
}
It’s quite terse, isn’t it. The typecasts make the whole thing a bit awkward (but generics to the rescue). Just feel the power of closures. And of course I don’t want to deprive you of the output of the lines above:
[Hund, Huhn] [HUND, KATZE, HUHN]
It’s been around for almost 30 years, but nobody told us! Martin Fowler recently wrote about these idioms in ruby/ smalltalk.
Leave a Reply