Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: GROOVY-6516


Code Block
def map4= [:]
map4[ 1 ]= 'a'
map4[ 2 ]= 'b'
map4[ true ]= 'p' //we can use boolean values as a key
map4[ false ]= 'q'
map4[ null ]= 'x' //we can also use null as a key
map4[ 'null' ]= 'z'
assert map4 == [1:'a', 2:'b', (true):'p', (false):'q', (null):'x', 'null':'z' ]

We can also use the '+' and '<<' operators to add elements to the map. Note that '<<' produces modifies the map while '+=' creates a new map:

Code Block
def map4a = [:]
def map5a = map4a
map4a << ['b':'b value']
map4a+= ['a':'a value'] // map4a is not the original map4a anymore
assert !
assert map4a == [b:'b value', a:'a value']
assert map5a == [b:'b value']

To use the value of a String as the key value of a map, simply surround the variable with parenthesis.