Hiteshkumar Misro Hiteshkumar Misro - 1 year ago 50
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);

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


1 Laptop

3 Mobile

4 PC

11 Tab

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

// clear first map and store pairs of hm2

// clear second map and store pairs of tempMap

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