Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - Integer or non String key in Map Literal

Tags:

groovy

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?

like image 612
Abbas Gadhia Avatar asked Sep 25 '16 15:09

Abbas Gadhia


1 Answers

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]

Output

3

We can even have the variables as key

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

println sampleMap[mapKey]

Output

5
like image 170
Prakash Thete Avatar answered Dec 18 '22 13:12

Prakash Thete