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.
- Ofc it must be a single, short expression
- For performance reasons, creating a deepcopy on that map (so it could be updated) and using mentioned
get
is not a solution.
Equivalents in different languages:
- JavaScript:
map["someKey"] || "defaultValue"
- Scala:
map.getOrElse("someKey", "defaultValue")
- Python3:
map.get("someKey", "defaultValue")