ConcurrentHashMap putAll() method in Java
The java.util.concurrent.ConcurrentHashMap.putAll() is an in-built function in Java which is used for the copy operation. The method copies all of the elements i.e., the mappings, from one ConcurrentHashMap into another.
Syntax:
new_conn_hash_map.putAll(conn_hash_map)
Parameters: The function accepts a ConcurrentHashMap conn_hash_map as its only parameter and copies all its mappings with this map.
Return Value: The method does not return any values.
Exception: The function throws NullPointerException when the specified parameter is null.
Below programs illustrate the ConcurrentHashMap.putAll() method :
Program 1: This program involves mapping String Values to Integer Keys.
// Java Program Demonstrate putAll() // method of ConcurrentHashMap import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); chm.put( 100 , "Geeks" ); chm.put( 101 , "for" ); chm.put( 102 , "Geeks" ); chm.put( 103 , "Gfg" ); chm.put( 104 , "GFG" ); // Displaying the existing HashMap System.out.println( "Initial Mappings are: " + chm); ConcurrentHashMap<Integer, String> new_chm = new ConcurrentHashMap<Integer, String>(); new_chm.putAll(chm); // Displaying the new map System.out.println( "New mappings are: " + new_chm); } } |
Initial Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG} New mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG}
Program 2: This program involves mapping Integer Values to String Keys.
// Java Program Demonstrate putAll() // method of ConcurrentHashMap import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<String, Integer>(); chm.put( "Gfg" , 100 ); chm.put( "GFG" , 102 ); chm.put( "GfG" , 18 ); chm.put( "gfg" , 15 ); chm.put( "gfG" , 55 ); // Displaying the existing HashMap System.out.println( "Initial Mappings are: " + chm); ConcurrentHashMap<String, Integer> new_chm = new ConcurrentHashMap<String, Integer>(); // Copying the contents new_chm.putAll(chm); // Inserting a new mapping new_chm.put( "gFg" , 22 ); // Displaying the new map System.out.println( "New mappings are: " + new_chm); } } |
Initial Mappings are: {Gfg=100, GFG=102, GfG=18, gfg=15, gfG=55} New mappings are: {Gfg=100, GFG=102, GfG=18, gfg=15, gfG=55, gFg=22}
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#putAll()