2

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?

Szymon Stepniak
42.5k10 gold badges117 silver badges140 bronze badges
asked Mar 8, 2019 at 13:10
2
  • Boggles the mind why anyone would design a map and look up something by "value" why don’t you invert the map? Commented 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. Commented Mar 8, 2019 at 14:11

1 Answer 1

4

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.

answered Mar 8, 2019 at 13:14

1 Comment

Thanks a lot, it works well. I was really close but my knowledges about Groovy are low. Thanks again :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.