實現方式是經過 putAll() 方法將多個 map 對象中的數據放到另一個全新的 map 對象中,代碼以下所示,展現了兩個 map 對象的合併,若是是多個 map 合併也是用這種方式。code
public static void main(String[] args) { Map<String, String> map1 = new HashMap<String, String>(); map1.put("one", "一"); map1.put("two", "二"); map1.put("three", "三"); Map<String, String> map2 = new HashMap<String, String>(); map1.put("ten", "十"); map1.put("nine", "九"); map1.put("eight", "八"); // 合併 Map<String, String> combineResultMap = new HashMap<String, String>(); combineResultMap.putAll(map1); combineResultMap.putAll(map2); // 合併後打印出全部內容 for (Map.Entry<String, String> entry : combineResultMap.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } }
合併後的 map 對象打印結果以下:對象