Wednesday, December 3, 2008

Groovy Closures


def doSomething(toMe, doThis){
toMe.each(doThis)
}
doSomething(['a','b','c','d']){print it + " "} /* print this list */
doSomething("\n"){print it} /*just print next line*/
doSomething(5){print (it * 2)}/* print that number * 2 */
doSomething("\n"){print it}
HashMap map = new HashMap(); /*So we can intermix Java in Groovy, hummm*/
//def map = [:] /* This is Groovy type map, works as well */
def string = "This is really really a test , really test !" /*could be read from a file*/
def tokens = string.tokenize()
doSomething(tokens){map[it] = map.get(it,0) + 1}
/* this is little tricky
doSomething with the tokens, what ?
doThis = put the tokens frequency in the map.
Qs: doSomething doesnot know about map, map is not in the scope of doSomething.
As: doSomething doesnot know about the map, but doThis closure does [map object is in scope of declared closure.]
*/
def keyList = map.keySet().toList(); /* Get the list from keyset */
keyList.sort{1-map[it]} /*sort in reverse order of maps words frequency */
doSomething(0..10){print "--"}
doSomething("\n"){print it}
doSomething(keyList){println it + " : " + map[it]} /*print the map*/


================ Result ===================

a b c d
10
----------------------
really : 3
test : 2
a : 1
! : 1
This : 1
is : 1
, : 1