You forgot to mention what happens when the key doesn't exist. I'm going to assume null
is Ok.
Groovy maps can be queried using property notation. So you can just do:
def x = mymap.likes
In this case, x
will contain the value of mymap['likes']
if it exists, otherwise it will be null.
If the key you are looking for (for example 'likes.key'
) contains a dot itself, then you can quote the key like so:
def x = mymap.'likes.key'
If the key is stored in a variable, use string interpolation with the property notation like so:
def key = 'likes'
def x = mymap."$key"
If you don't like null
, then use you use the elvis operator to assign a default value instead (similar to java.util.Map.getOrDefault
):
def x = mymap.someKey ?: 'default value'
Now you know all the secrets.
Remember that groovy maps are still just Java maps with "enhancements", so the rules that apply to Java still apply to groovy. Notably the java.util.Map
interface has a note in there that says:
Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException
or ClassCastException
. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.
Basically this says: Not all maps are the same, so make sure you somewhat know the kind of map you are dealing with (internally) as you attempt these operations on them. It shouldn't be a problem for simple stuff because Groovy by default uses java.util.LinkedHashMap
.