How to merge two nested maps with same keys and keep the values

אברגיל יעקובו :

I have the following maps:

Map<String,Map<String,Long>> mapOne;
Map<String,Map<String,Long>> mapTwo;

The values inside these maps look something like :

{
     BMW = {
        SIZE=1, 
        SPEED=60
    }, 
     AUDI = {
        SIZE=5, 
        SPEED=21
    },
     SEAT= {
        SPEED=15
     }
}

Second map:

 {
         Suzuki = {
            WHEELS_SIZE=2, 
            DOORS=3
        }, 
         AUDI = {
            WHEELS_SIZE=5, 
            DOORS=5
        },
         SEAT= {
            DOORS=4
         }
    }

I want the map after the merge to be :

{
         BMW = {
            SIZE=1, 
            SPEED=60
        }, 
         AUDI = {
            SIZE=5, 
            SPEED=21,
            WHEELS_SIZE=5, 
            DOORS=5
        },
         SEAT= {
            SPEED=15,
            DOORS=4
         },
         Suzuki = {
            WHEELS_SIZE=2, 
            DOORS=3
        }, 
    }

So I want to do the merge, and combine the values of duplicate keys. I believe it should be something like this:

mapTwo.forEach((k, v) -> mapOne.merge(k, v, ..... ));
Eran :

You can write:

mapTwo.forEach((k, v) -> mapOne.merge(k, v, (v1,v2) -> {
                                                          v1.putAll(v2);
                                                          return v1;
                                                       }));

This will modify mapOne to include the entries of mapTwo, while merging the inner Maps of common keys.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=69882&siteId=1