1. 程式人生 > >hashmap反轉 (鍵值對反轉)

hashmap反轉 (鍵值對反轉)

由於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);
	}
}