I learned this pretty neat feature when working with Maps which otherwise puts you on the Java path in Groovy which Groovy coders do not like ;)
Let's say that you are building a Map from some data sets and the value of the map entry is a List of some data, basically a Collection.
Without knowing this groovy method of Map, one would be writing code like:
Let's say that you are building a Map from some data sets and the value of the map entry is a List of some data, basically a Collection.
Without knowing this groovy method of Map, one would be writing code like:
//Groovy, but not so Groovy
Map map = [:]
def keys = ['a','b']
keys.each{ key->
if (map[key]) {
map[key] << 1
}
else {
map[key] = [1]
}
}
println map
//Groovier
//initialize Map with default closure for key not found
Map m = [:].withDefault{ [] } //withDefault in this case takes a closure that returns when a key is not found
keys.each{ key->
m[key] << 1
}
println m
No comments:
Post a Comment