Groovy map creation, use the value assigned to the previous key

Is there a way to use the values ​​assigned to the previous key on the map, for example:

def x = [
        a: someList.sum(),
        b: anotherList.sum(),
        c: someList.sum() / anotherList.sum()
]

I want the value of 'c' to be a / b, so there is a shortcut, so I don't need to recalculate the amounts when calculating 'c'

+4
source share
1 answer

To use the previously added key / values ​​to calculate the new key / values, you must be able to control the order in which the keys / values ​​are added. I know this is obvious, but what may not be obvious is that Groovy ads are Mapnot order-specific. For example, if you write this ...

def x = [
        a: 8,
        b: 2,
        c: a / b
]

... c, Groovy a, , variable/ . :

def x = [:].with {
    a = 8
    b = 2
    c = a / b

    delegate
}

Map. with(Closure) putAt() get() Map. ...

def x = [:].with {
    putAt('a', 8)
    putAt('b', 2)
    putAt('c', get('a') / get('b'))

    delegate
}

, Map, x.

+6

All Articles