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

后端 未结 5 1725
我寻月下人不归
我寻月下人不归 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:34

    The reason you get a Null Pointer Exception is because there is no key likesZZZ in your second example. Try:

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

提交回复
热议问题