groovy:在地图中找到一个键,并返回其值 [英] groovy: find a key in a map and return its value
问题描述
我想在给定地图中找到特定键。如果找到了键,我就想从地图中获取该键的值。
这是我到目前为止管理的:
def mymap = [name:Gromit,likes:cheese,id:1234]
def x = mymap。 find {it.key ==likes}
if(x)
println x.value
这样工作,输出是奶酪的预期。很好,但我不想在最后做 x.value
,我不想做 if(x)
。我想让x以某种方式直接包含这个值。
我无法直接将值直接写入x:
def mymap = [name:Gromit,likes:cheese,id:1234]
def x = mymap.find {it.key ==likesZZZ} .value
println x
在这种情况下,closure是null,这导致空指针异常。当然,上面的代码片段工作时 it.key ==likes
,但我不确定我会在地图中总是找到目标键。 p>
什么是Groovier和在地图上安全的方式:
- 检查地图是否有给定的键
- 如果是,请获取此键的值
使用地图的重点是直接访问。如果你确定地图中的值肯定不会是Groovy - false
,那么你可以这样做:
def mymap = [name:Gromit,likes:cheese,id:1234]
def key =likes
if (mymap [key]){
println mymap [key]
}
但是,如果值可能为Groovy - false
,则应使用:
if(mymap.containsKey(key)){
println mymap [key]
}
b $ b
最简单的解决方案,如果你知道这个值不是Groovy - false
(或者你可以忽略)默认值如下:
def value = mymap [key]?:default
这三个解决方案都明显比你的示例快,因为他们不扫描整个地图的键。他们利用 HashMap
(或 LinkedHashMap
)设计,使得直接密钥访问几乎是即时的。
I want to find a specific key in a given map. If the key is found, I then want to get the value of that key from the map.
This is what I managed so far:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likes" }
if(x)
println x.value
This works, the output is "cheese" as expected. Great, but I don't want to do x.value
at the end, and I don't want to do if(x)
. I want x to directly contain the value somehow.
I can't get the value directly into x like this:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likesZZZ" }.value
println x
Because the find closure is null in this case, this results in a Null Pointer Exception. Of course, the above code snippet works when it.key == "likes"
, but I am not sure that I will always find the target key in the map.
What is a "Groovier" and safe way to do this on a map:
- Check if a map has a given key,
- And if so, get the value of this key
The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false
, then you can do this:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"
if(mymap[key]) {
println mymap[key]
}
However, if the value could potentially be Groovy-false
, you should use:
if(mymap.containsKey(key)) {
println mymap[key]
}
The easiest solution, though, if you know the value isn't going to be Groovy-false
(or you can ignore that), and want a default value, is like this:
def value = mymap[key] ?: "default"
All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap
(or LinkedHashMap
) design that makes direct key access nearly instantaneous.
这篇关于groovy:在地图中找到一个键,并返回其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!