Tuesday, March 29, 2011

Map/Reduce Constructs

.collect() & .inject():

def map1 = { it -> it > 5 ? it * 2 : it * 10 }
def reduce1 = { coll, i -> if (i > 29) coll << i; coll }

println ([1,2,3,4,5,6,7,8,11,88].collect(map1).inject([], reduce1))

def map2 = { it -> it.value *= 2; it }
def reduce2 = { coll, me -> String key = me.key[0]; coll[key] = coll[key] ?: 0; coll[key] += me.value; coll }

println ([a1:1,b1:2,a2:3,b2:4].collect(map2).inject([:], reduce2))

http://groovyconsole.appspot.com/script/450002

No comments:

Post a Comment