Reputation: 3461
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. 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
Upvotes: 2
Views: 1748
Reputation: 337
// 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;
Upvotes: 3
Reputation: 248
tmp can be used to swap references as below.
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");
HashMap tmp = new HashMap();
tmp = hm;
hm = hm2;
hm2 = tmp;
for(Map.Entry en:hm.entrySet()){
System.out.println(en.getKey() + " " + en.getValue());
}
for(Map.Entry en:hm2.entrySet()){
System.out.println(en.getKey() + " " + en.getValue());
}
Upvotes: 2