Groovy从列表创建Map

yfjy0ee7  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(217)

我尝试在Groovy中从两个带有list的文件创建Map(或关联数组),但结果不是我所期望的。

def componentsFile = "WORKSPACE/Components" 
def linksFile = "WORKSPACE/Links"

def components = new File(componentsFile).collect { it.trim() } 
def links = new File(linksFile).collect { it.trim() } 

def result = [components, links].transpose().collect { component, link -> 
  [name: component, link: link]
}

println result

我得到的

[[name:component1, component2, component3, component4, link: link1, link2, link3, link4]]

我所期望的

[[name:component1, link:link1], [name:component2, link:link2], [name:component3, link:link3], [name:component4, link:link4]]
i7uq4tfw

i7uq4tfw1#

你试图转置包含逗号分隔值的字符串,因此你只在输出中得到2个字段。
你需要提前拆分字符串:

def components = 'component1, component2, component3, component4'
def links = 'link1, link2, link3, link4'

def result = [ components.split( ', ' ), links.split( ', ' ) ].transpose().collect{ component, link -> [name: component, link: link] }

assert result.toString() == '[[name:component1, link:link1], [name:component2, link:link2], [name:component3, link:link3], [name:component4, link:link4]]'

或者对于您的文件(我无法在控制台中复制),var的声明如下所示:

def components = new File(componentsFile).text.split( ', ' )
def links = new File(linksFile).text.split( ', ' )

相关问题