The Kaptain on … stuff

08 Feb, 2009

My favorite new Groovy trick

Posted by: TheKaptain In: Development

I program primarily in Java, but I must admit I’m a bit of a fanboy when it comes to the Groovy language. The syntatic sugar helps reduce some of the overhead of doing what should be simple things in Java, like reading Files or parsing XML. In particular the additions to the Collections API make things like creating populated data structures and iteration a breeze.

The Groovy Map API adds a very handy method which allows for specifying a default value on get() for when the Map key may or may not exist. I find this particularly useful for those all too common occasions you need to count occurences of things in a particular domain.
[groovy]
//
/**
* Looks up an item in a Map for the given key and returns the value – unless there is no entry for the given key in which case add the default value to the map and return that
*/
get(Object key, Object defaultValue)
[/groovy]

And you can use it like this
[groovy]
/* Counting using a map*/
def map = [:]
collection.each{
map[it] = map.get(it, 0) + 1
}
[/groovy]
Java has this ability for a Properties object but they still haven’t gotten around to adding it to Collections. I’ve seen different ways to accomplish the same thing using commons-collections or Google collections, but this is probably the easiest I’ve used. Thankfully Groovy and Java are pretty much interchangeable, at least for my uses, so I’ll just continue to try and pick the right one for the right job.

Reblog this post [with Zemanta]

No Responses to "My favorite new Groovy trick"

Comment Form