Skip to content
Related Articles

Related Articles

How to Copy Map Content to Another Hashtable in Java?
  • Last Updated : 07 Jan, 2021

The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.  

HashMap and Hashtable are used to store data in key and value form using a hashing technique to store unique keys. To copy Map content to another Hashtable in Java putAll() method is used.

putAll() method: The method copies all the mappings from the specified hashmap to the hashtable. These mappings replace any mappings that this hash table had for any of the keys currently in the specified hashmap.

Syntax:

hashtable.putAll(hashmap)

Parameters: The method takes one parameter hashmap that refers to the existing map we want to copy from.



Return Value: The method does not return any values.

Exception: The method throws NullPointerException if the map we want to copy from is null.

Steps in Copying HashMap elements to a Hashtable

  • Create a new HashMap and add some elements
  • Put mappings into HashMap
  • Create a new Hashtable.
  • Use putAll() method to copy elements from HashMap to Hashtable

Example:

Input:


hs.put("first", "Geeks");
hs.put("second", "for");
hs.put("third", "Geeks");


Output:

{third=Geeks, second=for, first=Geeks}
{g2=g2 ans, g1=g1 ans, third=Geeks, second=for, first=Geeks}

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to copy Map content to another Hashtable
  
import java.util.HashMap;
import java.util.Hashtable;
public class NewExample {
    public static void main(String a[])
    {
        // Create hashmap and insert elements
        HashMap<String, String> hashmap
            = new HashMap<String, String>();
  
        // Add mappings
        hashmap.put("k1", "GeeksForGeeks");
        hashmap.put("k2", "New Year");
  
        // Create hashtable
        Hashtable<String, String> hashtable
            = new Hashtable<String, String>();
  
        // Use putAll to copy Map elements to hashtable.
        hashtable.putAll(hashmap);
  
        // Print hashtable elements
        System.out.println("Hashtable elements: "
                           + hashtable);
    }
}

chevron_right


Output

Hashtable elements: {k2=New Year, k1=GeeksForGeeks}

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :