初始化/添加作为Groovy中的列表的Map值的最佳方法

Jos*_*ehl 4 groovy

我发现自己反复编写这段代码:

map[id] = map[id]  ?  map[id] + newListItem : [newListItem]
Run Code Online (Sandbox Code Playgroud)

有没有更简洁的方法将值初始化为List或添加到现有列表?

tim*_*tes 10

另一种方法是Map.withDefault像这样使用(以Ted为例):

def map = [:].withDefault { [] }
def id = 'foo'
def newListItem = 'bar'

map[id] << newListItem

assert map[id] == ['bar']

map[id] << newListItem

assert map[id] == ['bar', 'bar']
Run Code Online (Sandbox Code Playgroud)