Tuesday 4 December 2012

How to copy Key Value Elements from one Hash Table to the other HT

Leave a Comment

Try something like this.
Hashtable h = new Hashtable();
Hashtable h1 = new Hashtable();
Hashtable h2 = new Hashtable();
Set s = h.keySet();
int i = 0;
for (Object key : s) {
    if ( i++ < 3) {
        h1.put(key, h.get(key));
    } else {
        h2.put(key, h.get(key));
    }
}
Add generics etc. as appropriate.

Example:

String key = "hello";
Multimap<String, Integer> myMap = HashMultimap.create();
myMap.put(key, 1);
myMap.put(key, 5000);
System.out.println(myMap.get(key)); // prints either "[1, 5000]" or "[5000, 1]"
myMap = ArrayListMultimap.create();
myMap.put(key, 1);
myMap.put(key, 5000);
System.out.println(myMap.get(key)); // always prints "[1, 5000]"
Note that Multimap is not an exact equivalent of the home-baked solution; Hashtable synchronizes all its methods, while Multimap makes no such guarantee. This means that using a Multimap may cause you problems if you are using it on multiple threads. If your map is used only on one thread, it will make no difference (and you should have been using HashMap instead of Hashtable anyway).


0 comments:

Post a Comment