Java --如何合併兩個 Map ,putAll 的用法

兩個集合具有不同的 key

 HashMap map1=new HashMap();
 map1.put("1", "A");
 HashMap map2 = new HashMap();
 map2.put("2", "B");
 map2.put("3", "C");
 map1.putAll(map2);
 System.out.println(map1);

輸出結果: {3=C, 2=B, 1=A}

兩個集合具有重複的 key

HashMap map3=new HashMap();
map3.put("1", "A");
HashMap map4 = new HashMap();
map4.put("1", "B");
map4.put("3", "C");
map3.putAll(map4);
System.out.println(map3);

輸出結果: {3=C, 1=B}

結論:putAll 方法可以合併兩個 Map,只不過如果兩個集合有相同的 key,則用後面的覆蓋前面的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章