我发现自己反复编写此代码:
map[id] = map[id] ? map[id] + newListItem : [newListItem]
是否有更简洁的方法将值初始化为 List 或添加到现有列表?
最佳答案
另一种方法是像这样使用 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']
关于groovy - 初始化/添加到 Groovy 中列表的 Map 值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6119282/