monda
monda

Reputation: 3915

Create Map from existing Map in Groovy

I have a Map

[email:[[email protected], [email protected]], jobTitle:[SE, SD], isLaptopRequired:[on, on], phone:[9908899876, 7765666543], name:[hus, Vin]]

for which i need to have a another Map like

[hus:[[email protected],SE,99087665343],vin:[[email protected],SE,7765666543]] 

How can do it in Groovy?

Upvotes: 0

Views: 752

Answers (2)

rxn1d
rxn1d

Reputation: 1266

The most visual solution i have:

    def map = [email:['[email protected]', '[email protected]'], jobTitle:['SE', 'SD'], isLaptopRequired:['on', 'on'], phone:['9908899876', '7765666543'], name:['hus', 'Vin']]


    def names = map.name
    def emails = map.email
    def jobTitles = map.jobTitle
    def isLaptopRequireds = map.isLaptopRequired //sorry for the variable name
    def phones = map.phone

    def result = [:]
    for(i in 0..names.size()-1) {
        result << [(names[i]): [emails[i], jobTitles[i], isLaptopRequireds[i], phones[i]]]
    }
    assert result == [hus:['[email protected]', 'SE', 'on', '9908899876'], Vin:['[email protected]', 'SD', 'on', '7765666543']]
}

Upvotes: 0

tim_yates
tim_yates

Reputation: 171154

You could do it like:

def map = [email:['[email protected]', '[email protected]'], jobTitle:['SE', 'SD'], isLaptopRequired:['on', 'on'], phone:['9908899876', '7765666543'], name:['hus', 'Vin']]

def result = [:]

map.name.eachWithIndex { name, idx ->
  result << [ (name): map.values()*.getAt( idx ) - name ]
}

assert result == [hus:['[email protected]', 'SE', 'on', '9908899876'], Vin:['[email protected]', 'SD', 'on', '7765666543']]

Or, you could also do:

def result = [map.name,map.findAll { it.key != 'name' }.values().toList().transpose()].transpose().collectEntries()

But this is just less code at the expense of both readability and resource usage ;-)

Upvotes: 1

Related Questions