user3216060 user3216060 - 1 year ago 145
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"?

Answer Source

You can do:

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


someMap['key'] << someObject
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download