11
votes

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")
2
I wonder what do you have to smoke as a language designer to make you think it's a good idea that a 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 as sort sorting the underlying map or getMonth() returning values from 0 to 11... :(marc.guenther

2 Answers

15
votes

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

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

it will not add new key to the map.

14
votes

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'