apa64
apa64

Reputation: 1616

A Groovy way to add/assign a map key?

Is there a more "Groovy" way or a oneliner for doing this?

def map1 = [:], map2= [foo: "bar"]
if (map1.submap) {
    map1.submap << map2
}
else {
    map1.submap = map2
}

Upvotes: 1

Views: 183

Answers (1)

tim_yates
tim_yates

Reputation: 171054

use withDefault:

def map1 = map1.withDefault { [ foo: 'bar' ] } 

Upvotes: 1

Related Questions