I have a map looking like this:
def myMap = [
'Key1': ['nameOfApp', 'nameOfApp2', 'nameOfApp3'],
'Key5': ['nameOfApp4'],
'Key2': ['nameOfApp5'],
'Key3': ['xxx', 'yyy'],
'Key4': ['aaa', 'vvv']
]
How can I find the KEY by providing a VALUE (which is a simple String value) ? I've tried lots of things but I'm blocked with the fact that values are lists...
As an example, if I provide nameOfApp2
, I expect to get the key Key1
. What's the easiest way to achieve it with Groovy?
-
Boggles the mind why anyone would design a map and look up something by "value" why don’t you invert the map?Strelok– Strelok2019年03月08日 13:55:08 +00:00Commented Mar 8, 2019 at 13:55
-
The fact is that I can't update this part of the code because it's not on my scope. I'm using this map via Jenkins External Library.Tony Lecointre– Tony Lecointre2019年03月08日 14:11:50 +00:00Commented Mar 8, 2019 at 14:11
1 Answer 1
You can use find
method with a predicate like expectedValue in it.value
. Check the following example:
def myMap = [
'Key1': ['nameOfApp', 'nameOfApp2', 'nameOfApp3'],
'Key5': ['nameOfApp4'],
'Key2': ['nameOfApp5'],
'Key3': ['xxx', 'yyy'],
'Key4': ['aaa', 'vvv']
]
def expectedValue = 'nameOfApp2'
def key = myMap.find { expectedValue in it.value }?.key
assert key == 'Key1'
The variable it
inside the predicate closure represents each Map.Entry<String. List<String>>
from the input map, so you can check if the expected value is a part of it.value
list. And the last part uses ?.key
null safe operator to get the value of the key, just in case expected value is not present in any list.