最近工作中碰到了一个技术需求,需要将新获取的Map与之前的Map数据合并,两个Map中的数据的key值有重复。
要想保持数据完整,就需要将其中一个Map重复的key值改变。
经上网查询后,我发现改变的方案只有一种(我只找到一种),就是新建一个key-value对,然后再删除旧的key-value对。
下面是我测试写的代码。
public class Test{
public HashMap test1(){
HashMap hm = new HashMap();
HashMap hm1 = new HashMap();
HashMap hm2 = new HashMap();
hm1.put("Java","222");
hm1.put("PHP","111");
hm1.put("C++","333");
hm2.put("Java","aaa");
hm2.put("PHP","bbb");
hm2.put("C++","ccc");
hm.put("0",hm1);
hm.put("1",hm2);
return hm;
}
public HashMap test(){
HashMap hm = new HashMap();
HashMap hm1 = new HashMap();
HashMap hm2 = new HashMap();
hm1.put("Java","aaa");
hm1.put("PHP","222");
hm1.put("C++","555");
hm2.put("Java","abc");
hm2.put("PHP","123");
hm2.put("C++","234");
hm.put("0",hm1);
hm.put("1",hm2);
return hm;
}
public static void main(String[] args){
Test test = new Test();
HashMap hm = test .test();
HashMap hm1 = test .test1();
for(int i = 0;i < hm1.size();i++){
hm1.put(String.valueOf(hm.size()+i),hm1.get(String.valueOf(i)));
hm1.remove(String.valueOf(i));
}
hm.putAll(hm1);
System.out.println("最终 hm-->"+hm);
}
}
时间: 2024-11-11 05:39:36