Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Groovy map to key="value" string?

Tags:

groovy

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()
}
like image 637
LeslieV Avatar asked Jan 12 '16 17:01

LeslieV


1 Answers

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"'
like image 88
Will Avatar answered Nov 02 '22 19:11

Will