Saurabh Gaur
Saurabh Gaur

Reputation: 23805

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.

Upvotes: 3

Views: 5695

Answers (1)

Roger Glover
Roger Glover

Reputation: 3256

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

Upvotes: 6

Related Questions