Wednesday, November 4, 2009

Program to swap keys and values in HashMap

/**
* Program to swap keys and values in HashMap
* @author Akash
*/
import java.util.*;

// Program to swap keys and values in HashMap
public class ReverseMap
{
// This function takes HashMap as a input,
// swaps the keys and values and returns
// the HashMap with reversed keys and values.
public static Map reverseMap(Map m2)
{
Set s = new HashSet();
s = m2.keySet();
Iterator itr = s.iterator();
Map m3 = new HashMap();

while(itr.hasNext())
{
Object k = itr.next();
Object value = m2.get(k);
m3.put(value, k);
}

return m3;
}
// Prints all the values in HashMap
public static void printMap(Map m)
{
Set s = new HashSet();
s = m.keySet();
Iterator itr = s.iterator();
while(itr.hasNext())
{
Object o = itr.next();
System.out.println(o + " "+ m.get(o));
}
}
public static void main(String []args)
{
Map m = new HashMap();
Map m3 = new HashMap();

m.put("one", 1);
m.put("two", 2);
m.put("three", 3);
m3 = reverseMap(m);
printMap(m);
System.out.println();
printMap(m3);

}

}

No comments:

Post a Comment