简体   繁体   中英

groovy: how to compare keys of two maps, and combine values for output

I am attempting to match the keys of two separate maps (one of which has a nested list of values) and if the keys are identical, then take the values of each map and print them out.

    Map 1 = [1210910348504950525757554952 : 40_b4_f0_a4_9d_80]

    Map 2 = [1210910348504950525757554952:[1, 23230967]

As a result, I need to get an output that looks something like this:

    Map1Value.Map2(NestedValue1).Map2(NestedValue2)

    40_b4_f0_a4_9d_80.1.23230967

I can't figure out a way to do this.

So, I'm hoping you just have a simplistic example, and there are really more than just the one key in each of the maps.

If that's the case, maybe something like:

Map map1 = [ 444: 'aaa', 555: 'bbb', 666: 'zzz' ]
Map map2 = [ 444: [ 'cc', 'dd', 'ff' ], 666: ['111', '222'] ]

map1.keySet().each { key ->
    List v2 = map2[key]
    if ( v2 ) {
       println (([map1[key]] + v2).join("."))
    }
}

or something a little shorter even:

map1.keySet().intersect( map2.keySet() ).each { key ->
   println (([map1[key]] + map2[key]).join("."))
}

both of them output:

aaa.cc.dd.ff
zzz.111.222

Note that the 555 key did not match in the 2nd map, so it didn't output. Note I'm creating a list out of just the value from map1, then adding the list of values from map2 to it, then joining them with periods.

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