Groovy – How to get map value with default without updating the map

groovymap

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.

  1. Ofc it must be a single, short expression
  2. 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")

Best Answer

Use Java's getOrDefault Map method (since Java 8):

map.getOrDefault("someKey", "defaultValue")

it will not add new key to the map.

Related Topic