Reputation: 129
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.
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
Upvotes: 1
Views: 97
Reputation: 50285
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.
UPDATE:
Regarding JSON to Map
parsing, a JSON resonse can be easily parsed to Map
as shown below:
Map responseMap = new groovy.json.JsonSlurper().parseText( jsonResponseString )
Upvotes: 1