How to read value for the given key from a map, with providing a default value (used if the map doesn't contain entry for the specified key),
but without updating the map - this is what get
method does:
get(Object key, Object defaultValue)
Looks up an item in a Map for the given key and returns the value - unless there is no entry for the given key in which case add the default value to the map and return that.
get
is not a solution.Equivalents in different languages:
map["someKey"] || "defaultValue"
map.getOrElse("someKey", "defaultValue")
map.get("someKey", "defaultValue")
Use Java's getOrDefault Map method (since Java 8):
map.getOrDefault("someKey", "defaultValue")
it will not add new key to the map.
Given the examples you gave for some other languages and your expressed requirement to not update the Map, maybe you are looking for something like this...
map.someKey ?: 'default value'
Note that with that, if someKey does exist but the value in the Map associated with that key is null, or zero, false, or anything that evaluates to false per Groovy truth rules, then the default value will be returned, which may or may not be what you want.
An approach that is more verbose might be something like this...
map.containsKey('someKey') ? map.someKey : 'default value'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With