Last Updated : 11 Jul, 2025
The putAll() method of the Java HashMap class is used to copy all key-value mappings from another map to the existing map. If a key exists in both maps, its value is updated with the value from the source map. Otherwise, new key-value pairs are added.
Example 1: This example demonstrates copying all the key-value pairs from one HashMap to another.
Java
// Java program to demonstrates the
// working of HashMap putAll() method
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Create First HashMap
HashMap<Integer, String> hm1 = new HashMap<>();
hm1.put(1, "A");
hm1.put(2, "B");
System.out.println("HashMap: " + hm1);
// Create Second HashMap
HashMap<Integer, String> hm2 = new HashMap<>();
hm2.put(3, "C");
hm2.put(4, "D");
// Copy all mappings from m2 to m1
hm1.putAll(hm2);
System.out.println("Updated HashMap: " + hm1);
}
}
HashMap: {1=A, 2=B} Updated HashMap: {1=A, 2=B, 3=C, 4=D}Syntax of HashMap putAll() Method
public void putAll(Map map)
Parameter: The map whose mapping are copied into the HashMap.
Example 2: This example demonstrates If a key exists in both maps, its value is updated with the value from the source map.
Java
// Java program to demonstrates
// If a key exists in both the maps
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Create First HashMap
HashMap<Integer, String> hm1 = new HashMap<>();
hm1.put(1, "Geeks");
hm1.put(2, "For");
System.out.println("HashMap: " + hm1);
// Create Second HashMap
HashMap<Integer, String> hm2 = new HashMap<>();
// This key already exists in map1
hm2.put(2, "Geeks");
hm2.put(3, "Java");
// Copying m2 into m1
hm1.putAll(hm2);
System.out.println("Updated HashMap: " + hm1);
}
}
HashMap: {1=Geeks, 2=For} Updated HashMap: {1=Geeks, 2=Geeks, 3=Java}
Example 3: The below Java program demonstrates calling putAll(null) on a HashMap will throw a NullPointerException.
Java
// Java program demonstrates how
// putAll() throw NullPointerException
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> hm1 = new HashMap<>();
hm1.put(1, "Java");
// Passing null to putAll()
HashMap<Integer, String> hm2 = null;
hm1.putAll(hm2);
}
}
Output:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4