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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With