3

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.

Saurabh Gaur
  • 23,507
  • 10
  • 54
  • 73

1 Answers1

6

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
BalRog
  • 3,216
  • 23
  • 30
  • 1
    If the person who marked this down would be so kind as to comment on the shortcomings, I would appreciate it. – BalRog Sep 28 '16 at 15:08
  • 1
    I'm using similar method to get value (by `m.containsValue(value)` ). Appreciate for example. – Marslo Jan 19 '20 at 09:40