
Introduction
This program helps to reverse Key to Value and Value to Key for a Map Data Structure. There are various ways to write the program and the KW team will prepare a program using a few of them. Please find the program written in Java Programming Language below –
Program Code
package com.kw.sample;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
/**
* This class helps to explain reverse a Map.
*
*/
public class KWReverseMap {
/**
* This method helps to start the program execution.
*
* @param args
*/
public static void main(String[] args) {
System.out
.println("*********** Reverse Map Program Started *************");
// Instantiate Map object
Map<String, String> map = new HashMap<String, String>();
// Add the Key and Value
map.put("a", "1");
map.put("d", "1");
map.put("b", "2");
map.put("c", "3");
map.put("d", "4");
map.put("d", "41");
// Call the method to reverse the Map Key Value
reverseAMap1(map);
System.out.println(invertMap(map));
}
/**
* This method helps to reverse the Key to Value and Value to Key for a Map.
*
* @param map
*/
private static void reverseAMap1(Map map) {
System.out.println("+++++ Original Map Elements ++++++");
// Print the Map elements
System.out.println(map);
// Call method to revert the Map using invertMap from MapUtils class.
// This class available in Apace Common Jar file and it should be there
// in the class path.
Map<String, String> test1 = MapUtils.invertMap(map);
System.out.println("+++++ Map Elements After Reverse ++++++");
// Print the Map elements
System.out.println(test1);
}
/**
* This method helps to invert the Maps Key Value Pair interchangeable.
*
* @param <A>
* @param <B>
* @param map
* @return
*/
private static <A, B> Map<B, A> invertMap(Map<A, B> map) {
System.out.println("*********** invertMap Method *************");
Map<B, A> reverseMap = new HashMap();
for (Map.Entry<A, B> entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
return reverseMap;
}
}
Output
*** Reverse Map Program Started *** +++++ Original Map Elements ++++++ {d=41, b=2, c=3, a=1} +++++ Map Elements After Reverse ++++++ {3=c, 2=b, 1=a, 41=d} * invertMap Method *
{3=c, 2=b, 1=a, 41=d}
One thought on “Java Program to reverse a Map Key to Value and Value to Key”