Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize / addto Map values that are Lists in Groovy

Tags:

groovy

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?

like image 981
Josh Diehl Avatar asked Dec 06 '22 21:12

Josh Diehl


1 Answers

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']
like image 140
tim_yates Avatar answered Dec 21 '22 23:12

tim_yates