Reputation: 51
I have a map with another map as its value in Groovy.
Example:
[K1 : [k2:v2]]
Now I want find v2
using K1
key and have to return K1
.
I am using .each
loop but .each
loop continues to run until the end even if I return K1
in between.
Also I get the whole map as a return value though I expect only K1
key.
Upvotes: 1
Views: 2808
Reputation: 93
You can check this :
[K1: [k2: 'v2'], K3: [k4: 'v4']].find {'v2' in it.value.values() }?.key
Upvotes: 1
Reputation: 38619
The each
method as its name implies always goes through each and every element, the return value of the closure is ignored and the return value again is the complete map as you observed. This is the defined behavior for each
.
What you want to use is the find
method which finds the first entry that conforms to your criterion and then use its key like. Something like:
[K1: [k2: 'v2'], K3: [k4: 'v4']].find { it.value.k2 == 'v2' }.key
Upvotes: 0