Java: How to merge two hashmaps with the same Key saving the values of the first hashmap

Teachh :

I have two HashMaps<String><Integer>:

hm1 ={Value1=1,Value2=2,Value3=,3}

hm2 = {Value3=23,Value1=2,Value2=12}

OUTPUT:

hm3 = {Value1=2,Value2=12,Value3=23}

Thanks in advance!

dassum :

See if the below code solves your problem. You can use Java 8 merge function.

       //map 1
        HashMap<String, Integer> map1 = new LinkedHashMap<>();
        map1.put("Value1", 1);
        map1.put("Value2", 2);
        map1.put("Value3", 3);

        //map 2
        HashMap<String, Integer> map2 = new LinkedHashMap<>();
        map2.put("Value1", 2);
        map2.put("Value2", 12);
        map2.put("Value3", 23);

        HashMap<String, Integer> map3 = new LinkedHashMap<>(map1);
        //Merge maps
        map2.forEach((key, value) -> map3.merge(key, value, (v1, v2) -> v2)
        );
        System.out.println(map3);

Please check https://www.baeldung.com/java-merge-maps

Guess you like

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