从地图中获取密钥

时间:2022-03-13 18:31:54

I have a map like so:

我有一张这样的地图:

[One:[example:value1, example2:value2] ,Two[example 1:value3, example2:value4]]

I'm am matching value1 from a value in another map, but I need to get the keys,either One or Two depending on if it is a match.

我正在从另一个地图中的值匹配value1,但我需要获取一个或两个键,具体取决于它是否匹配。

So if I say:

所以,如果我说:

if( value1.equals (otherMapValue))
    Return One

This map is from a json response so if there is a better way to do this besides a map I can change it. Sorry for the formatting I'm using my phone

这个地图来自json响应,所以除了地图之外还有更好的方法可以改变它。对不起格式化我正在使用手机

1 个解决方案

#1


1  

This should do:

这应该做:

def someMethod(valueFromOthermap) {
    def map = [
        One: [example1: 'value1', example2:'value2'],
        Two: [example1: 'value3', example2:'value4']
    ]

    map.findResults { k, v ->
        valueFromOthermap in v.values() ? k : null
    }
}

assert someMethod('value1') == ['One']

If you are looking for the first matching key instead of a list of keys, then use findResult instead of findResults, everything else remains unchanged.

如果您正在寻找第一个匹配键而不是键列表,那么使用findResult而不是findResults,其他一切都保持不变。

UPDATE:
Regarding JSON to Map parsing, a JSON resonse can be easily parsed to Map as shown below:

更新:关于JSON to Map解析,可以很容易地将JSON共振解析为Map,如下所示:

Map responseMap = new groovy.json.JsonSlurper().parseText( jsonResponseString )

#1


1  

This should do:

这应该做:

def someMethod(valueFromOthermap) {
    def map = [
        One: [example1: 'value1', example2:'value2'],
        Two: [example1: 'value3', example2:'value4']
    ]

    map.findResults { k, v ->
        valueFromOthermap in v.values() ? k : null
    }
}

assert someMethod('value1') == ['One']

If you are looking for the first matching key instead of a list of keys, then use findResult instead of findResults, everything else remains unchanged.

如果您正在寻找第一个匹配键而不是键列表,那么使用findResult而不是findResults,其他一切都保持不变。

UPDATE:
Regarding JSON to Map parsing, a JSON resonse can be easily parsed to Map as shown below:

更新:关于JSON to Map解析,可以很容易地将JSON共振解析为Map,如下所示:

Map responseMap = new groovy.json.JsonSlurper().parseText( jsonResponseString )