Java:如何用同一个键合并两个hashmap并保存第一个hashmap的值

Java:如何用同一个键合并两个hashmap并保存第一个hashmap的值,java,Java,我有两个HashMaps: 输出: hm3 = {Value1=2,Value2=12,Value3=23} 提前谢谢 看看下面的代码是否解决了您的问题。您可以使用Java8合并函数 //map 1 HashMap<String, Integer> map1 = new LinkedHashMap<>(); map1.put("Value1", 1); map1.put("Value2", 2);

我有两个
HashMaps

输出:

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

提前谢谢

看看下面的代码是否解决了您的问题。您可以使用Java8合并函数

       //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);
//映射1
HashMap map1=新LinkedHashMap();
map1.put(“值1”,1);
map1.put(“值2”,2);
map1.put(“值3”,3);
//地图2
HashMap map2=新LinkedHashMap();
map2.put(“值1”,2);
map2.put(“值2”,12);
map2.put(“值3”,23);
HashMap map3=新的LinkedHashMap(map1);
//合并地图
map2.forEach((键,值)->map3.merge(键,值,(v1,v2)->v2)
);
系统输出打印LN(map3);
请检查

Map m1=new HashMap();
m1.认沽权(“a”、“1”);
m1.认沽权(“c”、“3”);
Map m2=新的HashMap();
m1.认沽权(“b”、“2”);
m1.认沽权(“d”、“4”);
映射m3=新树映射();
m3.putAll(m1);
m3.putAll(m2);
系统输出打印项次(m3);

2ndMap或第一个map的值。解释输出。如果可能的话,输出必须是hm1哈希映射的顺序。输出应该是第一个哈希映射的值,第二个哈希映射的键不清楚,请用问题中的示例进行解释。LinkedHashMap实现包含插入顺序,而不是键顺序。使用TreeMap实现获取按键排序的映射
       //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);
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);