简体   繁体   English

Groovy-地图文字中的整数或非字符串键

[英]Groovy - Integer or non String key in Map Literal

I'm trying to create a map of Integer vs Integer using Groovy literals ie 我正在尝试使用Groovy文字创建一个Integer vs Integer的映射,即

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? 如何使用地图文字将-3指定为键?

Well as stated in the groovy docs any non-string Map key should be specified in circular brackets(). 正如groovy文档中所述,任何非字符串Map键都应在圆括号()中指定。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM