簡體   English   中英

如何將Groovy映射轉換為key =“value”字符串?

[英]How to convert a Groovy map to key=“value” string?

我需要獲取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()
}

您可以使用所需的格式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"'

你可以使用groovy的map.toMapString()方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM