user3216060 user3216060 - 2 months ago 14
Groovy Question

Add element to list or create it if null?

I want to have a map that contains Lists as values. A working sample is this:

def someObject = 'foo'
def someMap = [:]
if (someMap['key'] == null) {
someMap['key'] = [someObject]
} else {
someMap['key'].add(someObject)
}


While this works, it's kind of annoying, because I need to differentiate between whether or not a list within the map has been created already. Does Groovy have a way to make this more "beautiful"?

Answer

You can do:

def someMap = [:].withDefault { [] }

Then

someMap['key'] << someObject
Comments