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

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

    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.

提交回复
热议问题