groovy:在地图上找到一个键并返回其值 [英] groovy: find a key in a map and return its value

查看:143
本文介绍了groovy:在地图上找到一个键并返回其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定的地图中找到一个特定的键。如果找到密钥,我想从地图中获取该密钥的值。



这是我到目前为止管理的:

  def mymap = [name:Gromit,喜欢:cheese,id:1234] 

def x = mymap。找到{it.key ==喜欢}

如果(x)
println x.value

这样做,输出是预期的奶酪。太好了,但我不想在最后做 x.value ,而且我不想做 if(x)。我想要x直接包含值。



我不能直接得到这个值,就像这样:



def mymap = [name:Gromit,喜欢:cheese,id:1234]

def x = mymap.find {it.key ==likesZZZ} .value

println x

因为找到在这种情况下,闭包为空,这将导致空指针异常。当然,当 it.key ==喜欢时,上述代码片段可以正常工作,但我不确定我会始终在地图中找到目标键。 p>

什么是Groovier和安全的方法来做到这一点:




  • 检查地图是否具有给定的键,如果是,则获取该键的值


解决方案

  def mymap = [name:Gromit,id:1234] 
def x = mymap.find {it。 key ==likes}?value
if(x)
printlnx value:$ {x}

println x.getClass()。name

?。检查null,不创建Groovy中例外。如果密钥不存在,结果将是一个 org.codehaus.groovy.runtime.NullObject


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

解决方案

def mymap = [name:"Gromit", id:1234]
def x = mymap.find{ it.key == "likes" }?.value
if(x)
    println "x value: ${x}"

println x.getClass().name

?. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆