Skip to Content

Create Java Hashtable from HashMap example

  1. /*
  2.   Create Java Hashtable from HashMap example
  3.   This Java Example shows how to copy all key value pairs from HashMap Object to
  4.   Hashtable Object using putAll method of java Hashtable class.
  5. */
  6.  
  7. import java.util.Enumeration;
  8. import java.util.Hashtable;
  9. import java.util.HashMap;
  10.  
  11. public class CreateHashtableFromHashMap {
  12.  
  13.   public static void main(String[] args) {
  14.    
  15.     //create HashMap
  16.     HashMap hMap = new HashMap();
  17.    
  18.     //populate HashMap
  19.     hMap.put("1","One");
  20.     hMap.put("2","Two");
  21.     hMap.put("3","Three");
  22.    
  23.     //create new Hashtable
  24.     Hashtable ht = new Hashtable();
  25.    
  26.     //populate Hashtable
  27.     ht.put("1","This value would be REPLACED !!");
  28.     ht.put("4","Four");
  29.    
  30.     //print values of Hashtable before copy from HashMap
  31.     System.out.println("Hashtable contents before copy");
  32.     Enumeration e = ht.elements();
  33.     while(e.hasMoreElements())
  34.       System.out.println(e.nextElement());
  35.    
  36.     /*
  37.       To copy values from HashMap to Hashtable use
  38.       void putAll(Map m) method of Hashtable class.
  39.      
  40.       Please note that this method will REPLACE existing mapping of
  41.       a key if any in the Hashtable
  42.     */
  43.    
  44.     ht.putAll(hMap);
  45.    
  46.     //display contents of Hashtable
  47.     System.out.println("Hashtable contents after copy");
  48.     e = ht.elements();
  49.     while(e.hasMoreElements())
  50.       System.out.println(e.nextElement());
  51.    
  52.   }
  53. }
  54.  
  55. /*
  56. Output would be
  57. Hashtable contents before copy
  58. Four
  59. This value would be REPLACED !!
  60. Hashtable contents after copy
  61. Four
  62. Three
  63. Two
  64. One
  65. */