简体   繁体   中英

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

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!

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

Map<String, String> m1 = new HashMap<>();
m1.put("a", "1");
m1.put("c", "3");

Map<String, String> m2 = new HashMap<>();
m1.put("b", "2");
m1.put("d", "4");

Map<String,String> m3 = new TreeMap<>();
m3.putAll(m1);
m3.putAll(m2);

System.out.println(m3);

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