0

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

Hexa
  • 87
  • 1
  • 2
  • 5

3 Answers3

2

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}"] }
David Maze
  • 130,717
  • 29
  • 175
  • 215
Paul King
  • 627
  • 4
  • 6
1

It cannot find sub field in your class, probably you want to have a string "sub"?

Basically, map entry can be declared in two ways:

Name: 'sub'

and

'Name': 'sub'

For the key it is assumed that is is a String, even if it is not wrapped by quotes.

But for the value it is mandatory to wrap in quotes. Otherwise, it is treated as a variable (or field)

Max Farsikov
  • 2,451
  • 19
  • 25
0

Given your desired results:

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

What you actually need to do is quote the entire item in each pair:

def m = [["Name:sub", "Value:23234"], ["Name:zoneinfo", "Value:Europe/London"]]
Trebla
  • 1,164
  • 1
  • 13
  • 28