Iqlaas Ismail
Iqlaas Ismail

Reputation: 405

Groovy Map: How to Get key from a value which in an array of strings

Hope this question finds you all well.

I have a map like this

def maps = 
[
    "hello": ["1", "2", "3"],
    "goodbye": ["4", "5", "6"]
]

By referring Map.Find, I tried to get the key hello by using value in the value array, for example string "2", but it did not return anything.

Here are what i have tried so far

def wishKey = maps.find{it.value == "1"}.key

def wishKey = maps.find{it.find{it.value == "1"}}.key

def wishKey = maps.find{it.find{it["1"]}.key

def wishKey = maps.find{it.value.find{it["1"]}.key

Is there something that I missed?

Any pointers would be great!

Additional Info: I'm trying to achieve this in JIRA ScriptRunner in their ScriptEditor using Behaviour Script.

While the maps are hardcoded because I'm trying to compare the value of a key with a value that I get from a custom field dropdown. I have confirmed that the custom field dropdown value is java.lang.String.

Upvotes: 1

Views: 1829

Answers (2)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27200

You could do something like this:

maps.findResult { 
    if(it.value.contains('2')) { it.key } 
}

Or this:

maps.findResult { entry ->
    if(entry.value.contains('2')) { entry.key }
}

(This code assumes that all of the values are collections and skips any error handling to deal otherwise)

Upvotes: 0

ernest_k
ernest_k

Reputation: 45309

Your closures are just a little lost in the way they're searching for values. All of the following should work. The first thing I'd do is explicitly name inner closure parameters (more for readability)

maps.find{it.value.find{e -> e == '2'}}.key
maps.find{it.value.find{it == "2"}}.key //also works, but I wouldn't do this

You can also use other list methods

maps.find{it.value.contains("2")}.key
maps.find{it.value.indexOf("2") >= 0}.key

For a summary of what's wrong with the code:

def wishKey = maps.find{it.value == "1"}.key //compares list with "1"
def wishKey = maps.find{it.find{it.value == "1"}}.key //calls find on map entry
def wishKey = maps.find{it.find{it["1"]}.key //calls find on map entry
def wishKey = maps.find{it.value.find{it["1"]}.key //it["1"] slices strings

Upvotes: 1

Related Questions