开发者

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

开发者 https://www.devze.com 2023-01-15 23:30 出处:网络
This is OK def variables=[ [\'var1\':\'test1\'], [\'var2\':\'test2\'], [\'var3\':\'test3\'] ] println \"${variables.size()}\"

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

精彩评论

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