user3216060 user3216060 - 6 months ago 47
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 {

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"?


You can do:

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


someMap['key'] << someObject