How to use a variable for the key part of a map

Groovy

Groovy Problem Overview


Let's say I have

def A = "abc"
def X = "xyz"

how do I create a Map where, instead of

def map = [A:1, X:2]

I get instead the equivalent of writing

def map = [abc:1, xyz:2]

but can use a variables A and X for the key?

P.S.: Same question for the value part of the map.

Groovy Solutions


Solution 1 - Groovy

Use this:

def map = [(A):1, (X):2]

For the value-part it's even easier, since there is no automagic "convert text to string" happening:

def map = [keyA:A, keyX:X]

Solution 2 - Groovy

Further to Joachim's answer, if you want to add entries to an existing map and the keys are variables, use:

def map = [:]
def A = 'abc'
map[A] = 2

If you use:

map.A = 2

It is assumed that you want to use the literal string 'A' as the key (even though there is a variable named A in scope.

Update

As @tim_yates pointed out in a comment, a key variable will also be resolved if you use:

map."$A" = 2

though personally I prefer to use the [A] syntax because refactoring tools might miss the "$A" reference if the variable is renamed

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRayView Question on Stackoverflow
Solution 1 - GroovyJoachim SauerView Answer on Stackoverflow
Solution 2 - GroovyDónalView Answer on Stackoverflow