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

Say I have

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

how to create a Map where instead

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

Instead, I get the equivalent of a record

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

but can use variables A and X for the key?

PS: The same question for the meaningful part of the map.

+76
groovy
Oct 13 '11 at 6:41
source share
2 answers

Use this:

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

For the value part, this is even simpler because there is no automatic "convert text to string":

 def map = [keyA:A, keyX:X] 
+109
Oct 13 '11 at 6:44
source share

In addition 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 letter string 'A' as the key (although there is a variable called A. in the scope

Update

As @tim_yates noted in the comment, the key variable will also be allowed if you use:

 map."$A" = 2 

although I personally prefer to use the syntax [A] , as refactoring tools may skip the link "$A" if the variable is renamed

+15
Oct 13
source share



All Articles