首页 > 代码库 > 【方法2】删除Map中Value反复的记录,而且仅仅保留Key最小的那条记录

【方法2】删除Map中Value反复的记录,而且仅仅保留Key最小的那条记录

依据guigui111111的建议:先把Map按Key从大到小排序,然后再把Key和Value互换。这也是一种非常好的思路,我写了一下代码,顺便贴上来,供大家參考与分享。


package shuai.study.map;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * @author shengshu
 * 
 */
public class UniqueMap1 {

	// Transfer to sorted Map
	public static Map<String, String> transferToSortedMap(Map<String, String> map) {
		// Define comparator for TreeMap
		// Note: Sort according to descending, because retain the smaller Key's record when exchanging Map's Key and Value
		Map<String, String> sort_map = new TreeMap<String, String>(new Comparator<String>() {
			@Override
			public int compare(String key1, String key2) {
				return key2.hashCode() - key1.hashCode();
			}
		});

		sort_map.putAll(map);

		return sort_map;
	}

	// Exchange Map's Key and Value
	public static Map<String, String> exchangeMap(Map<String, String> map) {
		Map<String, String> exchange_map = new TreeMap<String, String>();

		for (String key : map.keySet()) {
			String value = http://www.mamicode.com/map.get(key);>

【方法2】删除Map中Value反复的记录,而且仅仅保留Key最小的那条记录