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:

lazycoder said...

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

ht.putAll(map);

that would work fine :)

Lavnish said...

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

Anonymous said...

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

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

Lavnish said...

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

Java List said...

Nice tip. putAll(map) seems better to me.

Thanks
difference between hashtable and hashmap

Lavnish said...

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);
}