`

合并map

阅读更多
----合并map---------------------

     Map map1=new HashMap();
           Map map2=new HashMap();
           Map map3=new HashMap();
           map1.put("1", "aa");
           map1.put("2", "aa");
           map2.put("1", "aa");
           map2.put("2", "aa");
           map3.put("3", "bb");
           map3.put("4", "bb");
           Map newMap=new HashMap();
           newMap.putAll(map1);
           newMap.putAll(map2);
           newMap.putAll(map3);
           System.out.println(newMap);



哪有上面他们说的那么麻烦,如下即可:
HashMap map=new HashMap();
map.put("1", "A");
HashMap map1 = new HashMap();
map1.put("2", "B");
map1.put("3", "C");
map.putAll(map1);
  System.out.println(map);

打印结果:
{3=C, 2=B, 1=A}
如果是如下:
HashMap map=new HashMap();
map.put("1", "A");
HashMap map1 = new HashMap();
map1.put("2", "B");
map1.put("1", "C");
map.putAll(map1);
System.out.println(map);
打印结果:
{2=B, 1=C}

所以说用putAll就可以合并两个MAP,只不过如果有相同的key那么用后面的覆盖前面的
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics