Wednesday, January 15, 2014

collectEntries - List to Map

List a = (1..50).toList()

Closure remainder = { return (it % 8) }

Map b = a.collectEntries{ i-> [(i.toString()) : remainder(i)]}

assert b['5'] == 5
assert b['7'] == 7
assert b['8'] == 0
assert b['17'] == 1
String last = b.keySet()[-1]
assert b[last] == 2 // [50:2]



a = ('a'..'z').toList()

Closure mult = { return (it * 8) }

b = a.collectEntries{ i-> [(i.toString()) : mult(i)]}

assert b['a'] == 'a'*8
last = b.keySet()[-1]
assert b[last] == 'z'*8 // [z:zzzzzzzz]

No comments:

Post a Comment