简体   繁体   中英

How to add age to ageList =[12,13,23]

may be too simple groovy question but....please help

i have a list like this:

def ageList =[12,13,23]

i want to get this:

def newAgeList =[age:12,age:13,age:23]

could some one help me out?

thank you so much!

Does this work for you?

def newAgeList = ageList.inject([:]) { map, item -> if (!map['age']) map['age'] = []; map['age'] << item; map }

his would result in: ['age':[12, 13, 23]]

Otherwise, you can get the literal value as something like:

def newAgeList = ageList.collect { "age:$it" }

his would result in: ['age:12', 'age:13', 'age:23']

A third option:

def newAgeList = ageList.collect { ['age':it] }

This would result in: [['age':12], ['age':13], ['age':23]]

Unfortunately, you can't do this as a map like you showed above as map keys must be unique.

Really it all depends on what you are trying to do with the result.

Don't know if this is possible since you want to use the same map key 'age' for three different values. You'll end up overwriting the existing value with a new value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM