由于HashMap中值是可以重复的,假设原Map为:
{1=周杰伦, 2=周杰伦, 3=李健, 4=庾澄庆, 5=周杰伦, 6=谢霆锋}
我们希望得到的Map为:
{庾澄庆=4, 周杰伦=1_2_5, 谢霆锋=6, 李健=3}
import org.junit.Test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by hantao5 on 2018/9/17.
*/
public class ReverseHashMap {
@Test
public void test() {
Map<Integer, String> map = new HashMap();
map.put(1,"周杰伦");
map.put(2,"周杰伦");
map.put(3,"李健");
map.put(4,"庾澄庆");
map.put(5,"周杰伦");
map.put(6,"谢霆锋");
System.out.println(map);
Map<String, String> reverseMap = new HashMap<String, String>();
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> next = (Map.Entry<Integer, String>)it.next();
if (reverseMap.containsKey(next.getValue())) {
StringBuffer sb = new StringBuffer(reverseMap.get(next.getValue()));
sb.append("_"+next.getKey());
reverseMap.put(next.getValue(),sb.toString());
} else {
reverseMap.put(next.getValue(),next.getKey()+"");
}
}
System.out.println(reverseMap);
}
}