Nerrve Nerrve - 1 year ago 150
Groovy Question

Groovy - Integer or non String key in Map Literal

I'm trying to create a map of Integer vs Integer using Groovy literals i.e

Map<Integer, Integer> map = [1:10, 2:30, -3:32]

However, i'm getting a compilation error. How do i specify -3 as a key using map literals?

Answer Source

Well as stated in the groovy docs any non-string Map key should be specified in circular brackets().

So you can create the map as below

Map sampleMap = [:]
sampleMap << [(1): 3]

You can access this maps key- values as we access normaly.

like below

println  sampleMap[1]



We can even have the variables as key

String mapKey = "firstKey"
sampleMap << [ (mapKey) : 5]

println sampleMap[mapKey]


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download