7
votes

I need to take map and convert it to a string with the key/value pairs separated into key="value". I can do the following, and this works, but is there a "groovier" way to make this happen?

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()
}
2
in case this is html (or xml), remember, that you might have to quote or even encode the values. - cfrick

2 Answers

16
votes

You can map.collect using the desired format:

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"'
3
votes

You can use groovy's map.toMapString() method.

Map fields = [class: 'blue', type:'sphere', size: 'large' ]
fields.toMapString()