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")
get()
method modifies the underlying map. Thanks for pointing this out, I didn't even know about it. I wonder how many people have been bitten by this. This is as stupid assort
sorting the underlying map orgetMonth()
returning values from0
to11
... :( – marc.guenther