Thursday, December 15, 2011

Multi-Assign, Transform Map Keys

(a,b,c) = [1,2]
assert a == 1
assert c == null

(a,b,c) = {[1,2]}()
assert a == 1
assert c == null

Map o = [a:1,b:2,c:3,d:4,aa:5]
// the objective it to keep only the keys with 'a', and uppercase them //

Map f1 = [:]
o.findAll { i -> i.key.contains('a') }
    .each { i -> f1[i.key.toUpperCase()] = i.value }
println f1 // [A:1, AA:5]

Map f2 = [:]
o.each { i ->
    if (i.key.contains('a'))
        f2[i.key.toUpperCase()] = i.value 
}
println f2 // [A:1, AA:5]

Map g1 = o
    .findAll { i -> i.key.contains('a') }
    .inject([:]) { m, i ->
        m[i.key.toUpperCase()] = i.value
        return m
    }
println g1 // [A:1, AA:5]

Map g2 = o
    .inject([:]) { m, i ->
        if (i.key.contains('a'))
            m[i.key.toUpperCase()] = i.value
        return m
    }
println g2 // [A:1, AA:5]

No comments:

Post a Comment