Thursday, January 22, 2009

Convert HashMap to HashTable

How will you convert a HashMap having null values and/or keys to a hash table ?


import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashTableHashMap
{

public static void main(String[] args) {
Map map = new HashMap();
map.put("a",null);
map.put("b","B");
map.put(null,"D");
System.out.println(map);
Hashtable ht = new Hashtable();
Set set = map.entrySet();
Iterator itr = set.iterator();
while(itr.hasNext()){
Map.Entry entry = (Map.Entry)itr.next();
Object key = entry.getKey();
Object val = entry.getValue();
if(key==null){
key = ""+null; // Or whatever you want
}
if(val==null){
val = ""+null; // Or whatever you want
}
ht.put(key,val);
}
System.out.println(ht);
}
}

6 comments:

  1. How about using the putAll(Map) method of a Hashtable

    ht.putAll(map);

    that would work fine :)

    ReplyDelete
  2. hi anurag thanks for the info
    I will ty this one out and post it accordingly

    ReplyDelete
  3. You can just instantiate a Hashtabe by passing it a Hashmap, thus:

    HashMap map = new HashMap();
    Hashtable ht = new Hashtable(map);

    ReplyDelete
  4. try doing that ...
    tell me whats the result u get ...
    u r in for a surprise !!

    ReplyDelete
  5. PutAll will give you a NPE

    public static void testThree() {
    Map map = new HashMap();
    Hashtable ht = new Hashtable();
    map.put("a",null);
    map.put("b","B");
    map.put(null,"D");
    ht.putAll(map);
    System.out.println(ht);
    }

    ReplyDelete