tags:

views:

52

answers:

2

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!

A: 

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.

armandino
thanks! how about using List.add() to create a new list? def rawLines = [1,2,3] def lines = [] rawLines.each { lines.add("good") } I tried above, not working..I'm just learning groovy....
john
+3  A: 

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.

ig0774
This is exactly what I'm looking for!!!Thank you a million!!!!!
john
Glad I could help!
ig0774