Mich
Mich

Reputation: 137

To generate a list for each map key as iterating through list?

I have a map and i need to insert a generated list to each map key in groovy as i am iterating through a list !

Code:

def myMap = [:]
    anotherList.each{
    object -> //here i do some work to get two elements
    def element1 = ..
    def element2 = ..

    // so here i need to generate a list for the two elements with index 0 and 1
    myMap[obejct]= ['list', my list] 
    }
   return myMap

Upvotes: 0

Views: 1356

Answers (2)

albciff
albciff

Reputation: 18507

You can create a map using [ key: value] notation. Since your value is an array of two elements you can simply create it using [element1,element2] notation, and then you can add the object to the map using << operator.

So this myMap << [ (object) : [element1,element2]] can do the job.

In your code:

   def myMap = [:]
    anotherList.each{
    object -> //here i do some work to get two elements
    def element1 = ..
    def element2 = ..

    // so here i need to generate a list for the two elements with index 0 and 1
     myMap << [ (object) :  [element1,element2]]
    }
   return myMap

Note that I use (object) to evaluate the key, because if I use directly object the literal is used as key in the map instead of the value.

Hope this helps,

UPDATED BASED ON OP COMMENT:

If I understand well your requirements you want that map keys are the index instead of the value isn't it? To do so you can use eachWithIndex instead of each for example:

def myMap = [:]
  def anotherList = ['a','b','c','d']
    anotherList.eachWithIndex{ object,index -> //here i do some work to get two elements
    def element1 = object + 'z'
    def element2 = object + 'x'

    // so here i need to generate a list for the two elements with index 0 and 1
     myMap << [ (index) :  [element1,element2]]
    }
   return myMap //Result: [0:[az, ax], 1:[bz, bx], 2:[cz, cx], 3:[dz, dx]]

Upvotes: 1

Danilo
Danilo

Reputation: 2686

You can use the method collect to go through your list and generate another list whose values depend on the original list (the reasoning you use inside this method is up to you. Here a small example:

    def originalList = [1,2,3]
    def result = originalList.collect{obj->
        def e1 = obj
        def e2 = obj*2
        [e1,e2]
    }
    println result //[[1,1],[2,4],[3,6]]

EDIT: Sorry, I overlooked the fact that you expect a map as result. Here is an approach similar to the one described above. In this case you use each to go through the elements of your list:

def originalList = [[name: 'franz', age: 12], [name: 'bepi', age: 20],[name: 'giovanni', age: 65]]
def result=[:]
originalList.each{obj->
    def e1 = obj.age
    def e2 = obj.age*2
    result.put(obj, [e1,e2]) //key, value
}
println result //[[name:franz, age:12]:[12, 24], [name:bepi, age:20]:[20, 40], [name:giovanni, age:65]:[65, 130]]

Upvotes: 1

Related Questions