开发者

very simple groovy, map and closure question, but what I'm doing wrong

This is OK

def variables=[
              ['var1':'test1'],
              ['var2':'test2'],
              ['var3':'test3']
              ]

println "${variables.size()}" 
variables.each{entry ->   
  println "${entry} "   
}

I got:

3
[var1:test1] 
[var2:test2] 
[var3:test3] 

but this caused problems

def variables=[
                  ['var1':'test1'],
                  ['var2':'test2'],
                  ['var3':'test3']
                  ]

    println "${variables.size()}" 
    variables.each{entry ->   
      println "${entry.key} "   
    }

since I got开发者_运维百科:

3
null 
null 
null 

I'm expecting:

3
var1
var2
var3 

what's wrong with my code?

thank you!!!


You want:

def variables=[
    'var1':'test1',
    'var2':'test2',
    'var3':'test3'
]

println variables.size()
variables.each{entry ->   
    println entry.key
}

Before you had an ArrayList containing three LinkedHashMap objects. The above code is a single LinkedHashMap with three entries. You also don't need string interpolation, so I removed it.


Matthew's solution works great, and it's probably what you wanted (a simpler data structure to begin with).

However, in case you really wanted variables to be a list of three maps (as per your question), then this how you could get your desired output:

def variables=[
      ['var1':'test1'],
      ['var2':'test2'],
      ['var3':'test3']
]

println "${variables.size()}" 

variables.each{ entry->
    entry.each {
        println it.key
    }
}

In the outer closure, every entry is a map. So we iterate through each of those maps using the inner closure. In this inner closure, every it closure-param is a key:value pair, so we just print its key using it.key.

Like Matthew, I've also removed the string interpolation since you don't need it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜