What is HashMap putAll() in Java?

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.

Syntax

new_hash_map.putAll(exist_hash_map)

Parameters and return value

Parameters

Only the exist_hash_map parameter is taken. It refers to the existing HashMap we want to copy.

Return value

There is no return value.

Code

Let’s have a look at a coding example of how to use this method to copy a HashMap.

// import the util lib from Java
import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
{
// Creating an empty HashMap based on our data
HashMap<Integer, String> fruit_prices = new HashMap<Integer, String>();
// Introduce some data in the hashmap
fruit_prices.put(10, "Apple");
fruit_prices.put(20, "Banana");
fruit_prices.put(30, "Orange");
// Lets have a look at the HashMap
System.out.println("Hashmap: "+ fruit_prices);
// Declaring another hashmap and applying putall
HashMap<Integer, String> Another_hashmap = new HashMap<Integer, String>();
Another_hashmap.putAll(fruit_prices);
// Lets have a look a look at the hashmap
System.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.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved