Rene Enriquez Rene Enriquez - 9 months ago 37
Groovy Question

Update all object fields with a same value in a Groovy map

I have an Object in Groovy like:

class Person {
def name
def age

And a collection of persons stored in a map:

Person a = new Person(name: 'A', age:29)
Person b = new Person(name: 'B', age:15)

Map persons = ['1':a, '2':b]

I'm trying to update the age field for all persons, I know that I can do something like:

persons.each{ k,v -> v.age=0 }

But, I was wondering if is there another way to do it without iterating the entire map. As you can see, all persons should have the same value


You can use the spread operator:

persons.values()*.age = 0