小编Les*_*ieV的帖子

Groovy:通过映射列表中的键查找/返回映射的值

我有一个地图列表,我想获取列表中的特定地图并返回给定键的值。我确信我缺少一些基本的东西,但我无法完成这项工作。我有几次失败的尝试:

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)

collections groovy dictionary

3
推荐指数
1
解决办法
5711
查看次数

如何将Groovy映射转换为key ="value"字符串?

我需要获取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)

groovy

2
推荐指数
1
解决办法
7445
查看次数

标签 统计

groovy ×2

collections ×1

dictionary ×1