I'm trying to create a map of Integer vs Integer using Groovy literals ie
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.