问题描述
我有一个 Map ,如下所示: - $ / $>
$ b
def map = [
a:a,
b:[f:f,g:g],
c:c,
d:d,
e:[h:h,i:[j:j]],
]
这里我想通过给定的键来搜索值。但问题是提供的关键是单个唯一键,而不是嵌套键层次结构,如下所示: -
println map.a
println map.j
这里输出如下: -
a
null
可以看到,我无法获取 j 键的值,我知道是因为此键不存在于根目录 Map 但它存在于嵌套 Map 中。如果我这样做: - $ / $>
println map.eij
它给了我正确的输出,但是我不知道这个键的层次结构。
有什么办法通过传递准确的关键字获得 map 的值
注意: - 所有密钥在提供的 Map 中都是唯一的。
简单的树遍历:
def findDeep(Map m,String key){
if(m.containsKey(key) )return m [key]
m.findResult {k,v - > v instanceof Map? findDeep(v,key):null}
}
考虑到您的输入映射,测试代码:
('a'..'k')。each {key - >
println$ {key}:$ {findDeep(map,key)}
}
产生以下结果:
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
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.
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
这篇关于如何从地图以及嵌套地图中按键搜索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!