groovy: safely find a key in a map and return its value

后端 未结 5 1885
我寻月下人不归
我寻月下人不归 2021-02-01 12:33

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:

         


        
5条回答
  •  没有蜡笔的小新
    2021-02-01 13:13

    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.

提交回复
热议问题