Hashmap class is a part of java.util package. In hashmap we can store key and value pairs , only with unique keys.If we try to insert a duplicate key it will replace the old value with new value. Many built-in methods are there in hashmap class which makes it easy to perform operations on them, like insertion , deletion and many more. One of those methods is Java Hashmap putAll() Method.
To know more about Hashmap putAll() Method read the complete article.
Java Hashmap putAll() Method
The hashmap putAll() method is used to copy mappings of existing hashmap to the new hashmap. This method does not returns any value. Below in this page you can find it’s syntax, return values, parameters with detailed examples.
Syntax :
new_hashmap.putAll(old_hashmap);
ParametersThis method takes one parameter:
old_hashmap : - hashmap whose mapping is to be copied into new new hashmap.
import java.util.*;
public class Main
{
public static void main (String[]args)
{
// Creating an empty HashMap
HashMap < String, Integer > hash_map_1 =
new HashMap < String, Integer > ();
// Mapping string values to int keys in a empty hashmap
hash_map_1.put ("Maths", 80);
hash_map_1.put ("English", 75);
hash_map_1.put ("Hindi", 85);
hash_map_1.put ("Science", 90);
System.out.println("Original hashmap : " + hash_map_1);
//copying mapping of existing hashmap to new hashmap
HashMap < String, Integer > new_hashmap = new HashMap < String, Integer >() ;
new_hashmap.putAll(hash_map_1);
System.out.println("New hashmap : "+ new_hashmap);
}
}
Output :
Original hashmap : {Maths=80, English=75, Science=90, Hindi=85}
New hashmap : {Science=90, Maths=80, English=75, Hindi=85}
What happened above : In the above example a hashmap is created, initially which is empty and elements are inserted in hash_map_1. Now a new hashmap is created and mappings of hash_map_1 is copied to new_hashmap using putAll() method.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment