groovy:安全地在地图中找到一个键并返回其值 [英] groovy: safely find a key in a map and return its value
问题描述
我想在给定的地图中找到特定的钥匙.如果找到了密钥,那么我想从地图上获取该密钥的值.
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
此方法有效,输出为预期的奶酪".很好,但是我不想最后做x.value
,也不想做if(x)
.我希望x以某种方式直接包含该值.
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.
我不能像这样直接将值获取到x中:
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
由于在这种情况下find闭包为null,因此将导致Null Pointer Exception.当然,上面的代码片段在it.key == "likes"
时有效,但是我不确定是否总是会在地图上找到目标键.
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.
在地图上执行此操作的"Groovier"是安全的方法:
What is a "Groovier" and safe way to do this on a map:
- 检查地图是否具有给定的键,
- 如果是这样,获取此键的值
推荐答案
def mymap = [name:"Gromit", id:1234]
def x = mymap.find{ it.key == "likes" }?.value
if(x)
println "x value: ${x}"
println x.getClass().name
?.
检查是否为空,并且不会在Groovy中创建异常.如果密钥不存在,则结果为org.codehaus.groovy.runtime.NullObject
.
?.
checks for null and does not create an exception in Groovy. If the key does not exist, the result will be a org.codehaus.groovy.runtime.NullObject
.
这篇关于groovy:安全地在地图中找到一个键并返回其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!