Hiteshkumar Misro Hiteshkumar Misro - 4 months ago 17
Java Question

Can I swap HashMap keys and values to other?

I'm new to Java and what I want to do is to swap all the keys and values of HashMap (hm) to HashMap (hm2) and vice versa. I didn't find any solution for this question, Is it possible?

import java.util.*;

class HashMapSwap{
public static void main(String args[]){
HashMap<Integer, String> hm = new HashMap<Integer, String>();
HashMap<Integer, String> hm2 = new HashMap<Integer, String>();

hm.put(3, "Mobile");
hm.put(11, "Tab");

hm2.put(4, "PC");
hm2.put(1, "Laptop");

Map tmp = new HashMap(hm);
tmp.keySet().removeAll(hm2.keySet());
hm2.putAll(tmp);

for(Map.Entry en:hm2.entrySet()){
System.out.println(en.getKey() + " " + en.getValue());
}
}
}


O/P:

1 Laptop

3 Mobile

4 PC

11 Tab

Answer
// store first map in (new) temporary map
HashMap<Integer, String> tempMap = new HashMap<Integer, String>(hm);

// clear first map and store pairs of hm2
hm.clear();
hm.putAll(hm2);

// clear second map and store pairs of tempMap
hm2.clear();
hm2.putAll(tempMap);

// EDIT (hint from Palcente)
// optional: null the tempMap afterwards
tempMap = null;