Saurabh Gaur Saurabh Gaur - 2 months ago 14
Groovy Question

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

I have a

Map
as below :-

def map = [
a:"a",
b:[f:"f", g:"g"],
c:"c",
d:"d",
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 :-

a
null


As you can see, I can't get value for
j
key, I know because this key is not present in root
Map
but it is present in nested
Map
. 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
map
by passing exact key only??

Note :- All keys are always unique in the provided
Map
.

Answer

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
Comments