Search code examples
grailsgroovyspockgroovy-console

Why map.collectEntries() not working for this data [[Name:sub, Value:23234]] - Groovy


Why this works:

def m =  [[1,11], [2,22], [3,33]]
println(m.collectEntries())

output: [1:11, 2:22, 3:33]

But this doesn't work:

def m = [[Name:sub, Value:23234], [Name:zoneinfo, Value:Europe/London]]

println(m.collectEntries())

output: groovy.lang.MissingPropertyException: No such property: sub for class

I want to process that map so that I get a list of key value pairs like this:

["Name:sub" :"Value:23234", "Name:zoneinfo": "Value:Europe/London"]

where Name:sub is the key and Value:23234 is the value.

Reference https://stackoverflow.com/a/34899177/9992516


Solution

  • In the second example sub and zoneinfo are being read as variable names, not strings, and you need to quote them.

    def m = [[Name:'sub', Value:23234], [Name:'zoneinfo', Value:'Europe/London']]
    println m.collectEntries{ ["Name:${it.Name}", "Value:${it.Value}"] }