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()
}
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"'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With