Rene Enriquez
Rene Enriquez

Reputation: 1599

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

Upvotes: 1

Views: 594

Answers (1)

cfrick
cfrick

Reputation: 37008

You can use the spread operator:

persons.values()*.age = 0

Upvotes: 5

Related Questions