简体   繁体   English

Groovy:通过在地图列表中键入键来查找/返回地图的值

[英]Groovy: Find/return the value of a map by key in a list of maps

I have a list of maps and I want to get a specific map on the list and return its value for a given key. 我有一个地图列表,我想在列表上获取特定的地图并返回给定键的值。 I'm sure there is something fundamental I am missing, but I cannot make this work. 我确定我缺少一些基本知识,但是我无法完成这项工作。 I have several failed attempts: 我有几次失败的尝试:

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 = favorites*.get('color').value
//        String favoriteColor = favorites.collect { it['color'] }.value as String
//        String favoriteColor = favorites.find { it['color'] }.value as String

        then:
        favoriteColor == 'yellow'
    }

Is there a clean way to make this work? 有一种干净的方法可以使这项工作吗?

你可以简单地做

String favoriteColour = favorites.findResult { it.color }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM