如何将Groovy映射转换为key ="value"字符串?

Les*_*ieV 2 groovy

我需要获取map并将其转换为一个字符串,其中键/值对分为key ="value".我可以做到以下,这是有效的,但是有一种"更加时髦"的方式来实现这一目标吗?

void "test map to string"() {
given: "a map"
Map fields = [class: 'blue', type:'sphere', size: 'large' ]

when:
StringBuilder stringBuilder = new StringBuilder()
fields.each() { attr ->
    stringBuilder.append(attr.key)
    stringBuilder.append("=")
    stringBuilder.append('"')
    stringBuilder.append(attr.value)
    stringBuilder.append('" ')
}

then: 'key/value pairs separated into key="value"'
'class="blue" type="sphere" size="large" ' == stringBuilder.toString()
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*ill 12

您可以map.collect使用所需的格式:

Map fields = [class: 'blue', type:'sphere', size: 'large' ]

toKeyValue = {
    it.collect { /$it.key="$it.value"/ } join " "
}

assert toKeyValue(fields) == 'class="blue" type="sphere" size="large"'
Run Code Online (Sandbox Code Playgroud)