【问题标题】:Groovy How to find key value in list of mapsGroovy 如何在地图列表中查找键值
【发布时间】:2021-12-17 09:38:58
【问题描述】:

我想找到一个比遍历地图列表更好的解决方案,如下所示:

[[name:"Gromit", likes:"cheese", id:1234],[name:"john", likes:"fries", id:1234],...]

我有一个名字列表,例如 ["lisa","carl","bob"...]。所以我想在地图列表中搜索与我的名字列表关联的“喜欢”和“id”,但我不想使用一些布尔代码遍历每个名​​字的列表。

对于常规地图,我想我可以这样做:

if(regularMap.containsKey(key)) {
    println regularmap[key]
}

如何对 Jenkins 声明式管道中的地图列表执行类似操作?

【问题讨论】:

    标签: arrays groovy associative-array jenkins-groovy


    【解决方案1】:

    目前尚不清楚您希望结果采用哪种形式,但以下是一个起点:

        def inputData = [[name: "Gromit", likes: "cheese", id: 1234], [name: "john", likes: "fries", id: 1234]]
        def names = ["lisa", "Gromit", "carl", "bob", "john",]
    
        def results = []
        names.each { name ->
            def matchingMap = inputData.find { it.name == name }
            if (matchingMap) {
                results << [matchingMap.id, matchingMap.likes]
            }
        }
        
    

    results 将是 [[1234, cheese], [1234, fries]]

    【讨论】:

      【解决方案2】:
      listOfMaps.findAll{ it.name in names }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-21
        • 2018-06-21
        相关资源
        最近更新 更多