Java HashMap putAll() Method Guide

The putAll() method of HashMap is used to add all key-value pairs from another Map to the current HashMap.

The syntax for using the putAll() method is as follows:

HashMap.putAll(Map<? extends K, ? extends V> map)

map is another Map that needs to be added to the current HashMap.

Here is an example of using the putAll() method:

HashMap<String, Integer> map1 = new HashMap<>();
map1.put("A", 1);
map1.put("B", 2);

HashMap<String, Integer> map2 = new HashMap<>();
map2.put("C", 3);
map2.put("D", 4);

map1.putAll(map2); // 将map2中的键值对添加到map1中

System.out.println(map1); // 输出: {A=1, B=2, C=3, D=4}

In the above example, two HashMap objects, map1 and map2, were first created, and then key-value pairs were added to map1 and map2 using the put() method. Finally, the putAll() method was used to add the key-value pairs from map2 to map1, thus achieving the merging of the two HashMaps.

bannerAds