Using the elvis (? :) operator is a bit more concise:
def map = [:]
def id = 'foo'
def newListItem = 'bar'
map[id] = (map[id] ?: []) << newListItem
assert map[id] == ['bar']
map[id] = (map[id] ?: []) << newListItem
assert map[id] == ['bar', 'bar']
Although, if speed is important, Kyle’s answer is a little faster, since he does not complete the assignment step (100,000 cycles were checked on my machine, its 1.36 s, and I have 1.46 s against 16.54 for the original).
source
share