从Groovy中的现有Map创建Map

时间:2013-09-02 12:33:22

标签: groovy

我有一张地图

[email:[hus@gmail.com, vin@gmail.com], jobTitle:[SE, SD], isLaptopRequired:[on, on], phone:[9908899876, 7765666543], name:[hus, Vin]]

我需要另一张地图

[hus:[hus@gmail.com,SE,99087665343],vin:[vin@gmail.com,SE,7765666543]] 

如何在Groovy中做到这一点?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

def map = [email:['hus@gmail.com', 'vin@gmail.com'], 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:['hus@gmail.com', 'SE', 'on', '9908899876'], Vin:['vin@gmail.com', 'SD', 'on', '7765666543']]

或者,你也可以这样做:

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

但这只是代码较少而牺牲了可读性和资源使用; - )

答案 1 :(得分:0)

我有最直观的解决方案:

    def map = [email:['hus@gmail.com', 'vin@gmail.com'], 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:['hus@gmail.com', 'SE', 'on', '9908899876'], Vin:['vin@gmail.com', 'SD', 'on', '7765666543']]
}