I find myself repeatedly writing this code:
map[id] = map[id] ? map[id] + newListItem : [newListItem]
Is there a more succinct way to initialize the value as a List or add to an existing list?
An alternative would be to use Map.withDefault
like so (taking Ted's example):
def map = [:].withDefault { [] }
def id = 'foo'
def newListItem = 'bar'
map[id] << newListItem
assert map[id] == ['bar']
map[id] << newListItem
assert map[id] == ['bar', 'bar']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With