Saurabh Gaur Saurabh Gaur - 1 year ago 114
Groovy Question

How to search value by key from Map as well as Nested Map

I have a

as below :-

def map = [
b:[f:"f", g:"g"],
e:[h:"h", i:[j:"j"]],

Here I want to search value by given key. But problem is provided key is single unique key instead of nested key hierarchy as below :-

println map.a
println map.j

Here output as expected :-


As you can see, I can't get value for
key, I know because this key is not present in root
but it is present in nested
. If I do as below :-

println map.e.i.j

It gives me correct output but I don't know this hierarchy of keys.

Is there any way to get value from above
by passing exact key only??

Note :- All keys are always unique in the provided

Answer Source

Write a simple tree traversal:

def findDeep(Map m, String key) {
    if (m.containsKey(key)) return m[key]
    m.findResult { k, v -> v instanceof Map ? findDeep(v, key) : null }

Given your input map, the following test code:

('a'..'k').each { key ->
    println "${key}: ${findDeep(map, key)}"

Yields the following results:

a: a
b: [f:f, g:g]
c: c
d: d
e: [h:h, i:[j:j]]
f: f
g: g
h: h
i: [j:j]
j: j
k: null
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download