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

1

6

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, ..... ));
Liriodendron answered 11/4, 2019 at 7:24 Comment(0)
T
4

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.

Toady answered 11/4, 2019 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.