gpt4 book ai didi

groovy - 初始化/添加到 Groovy 中列表的 Map 值的最佳方法

转载 作者:行者123 更新时间:2023-12-03 12:33:10 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com