The java.util.HashMap.putAll()
method is one of the built-in methods of the Java HashMap class. We normally use this to perform the operation of copying an existing map into another.
All the mappings for key-value pairs are copied from one HashMap to another using the putAll()
method.
If the existing map is NULL and a user tries to copy it, the program throws a
NullPointerException
.
new_hash_map.putAll(exist_hash_map)
Only the exist_hash_map
parameter is taken. It refers to the existing HashMap we want to copy.
There is no return value.
Let’s have a look at a coding example of how to use this method to copy a HashMap.
// import the util lib from Javaimport java.util.*;class HelloWorld {public static void main( String args[] ) {{// Creating an empty HashMap based on our dataHashMap<Integer, String> fruit_prices = new HashMap<Integer, String>();// Introduce some data in the hashmapfruit_prices.put(10, "Apple");fruit_prices.put(20, "Banana");fruit_prices.put(30, "Orange");// Lets have a look at the HashMapSystem.out.println("Hashmap: "+ fruit_prices);// Declaring another hashmap and applying putallHashMap<Integer, String> Another_hashmap = new HashMap<Integer, String>();Another_hashmap.putAll(fruit_prices);// Lets have a look a look at the hashmapSystem.out.println("After applying putAll method, Another_hashmap: " + Another_hashmap);}}}
If the new HashMap already contains a key that was also present in the original HashMap, the mapping in the new HashMap is replaced with the mapping from the original.