Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

map

groovy

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")
like image 258
vucalur Avatar asked Jun 17 '14 14:06

vucalur


2 Answers

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

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

it will not add new key to the map.

like image 164
user2650367 Avatar answered Nov 16 '22 02:11

user2650367


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'
like image 34
Jeff Scott Brown Avatar answered Nov 16 '22 04:11

Jeff Scott Brown