Tony Lecointre
Tony Lecointre

Reputation: 83

How to retrieve a key from the Map<String,List<String>> based on its value (an element of a list)?

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?

Upvotes: 2

Views: 94

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

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.

Upvotes: 4

Related Questions