我有一个地图列表,我想获取列表中的特定地图并返回给定键的值。我确信我缺少一些基本的东西,但我无法完成这项工作。我有几次失败的尝试:
void "find map by key in a list of maps"() {
given: "a list of maps"
List favorites = [
[fruit: 'apple'],
[color: 'yellow'],
[activity: 'reading']]
when:
String favoriteColor = favorites.each {
it.find { key, value ->
key == 'color'
return value
}
}
// String favoriteColor = favorites.each { it['color'] }
// String favoriteColor = favorites.find { it.key == 'color' }
// String favoriteColor = favorites.collect { it['color'] }
// String favoriteColor = favorites*.get('color')
// String favoriteColor = …Run Code Online (Sandbox Code Playgroud) 我需要获取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)