如何从地图以及嵌套地图中按键搜索值 [英] How to search value by key from Map as well as Nested Map
问题描述
我有一个 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
它给了我正确的输出,但是我不知道这个键的层次结构。
有什么办法通过传递准确的关键字获得 注意: - 所有密钥在提供的 简单的树遍历: 考虑到您的输入映射,测试代码: 产生以下结果: I have a 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 :- Here output as expected :- As you can see, I can't get value for It gives me correct output but I don't know this hierarchy of keys. Is there any way to get value from above Note :- All keys are always unique in the provided Write a simple tree traversal: Given your input map, the following test code: Yields the following results:
这篇关于如何从地图以及嵌套地图中按键搜索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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
Map
as below :-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
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
map
by passing exact key only??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