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

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

介绍

    晚上无聊的时候,我做了一个測试题,測试题的大体意思是:删除Map中Value反复的记录,而且仅仅保留Key最小的那条记录。

比如:

I have a map with duplicate values:

    ("A", "1");
    ("B", "2");
    ("C", "2");
    ("D", "3");
    ("E", "3");

I would like to the map to have:
    ("A", "1");
    ("B", "2");
    ("D", "3");


package shuai.study.map;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

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

	// Remove repetition from Map, this is core part in this Class
	public static Map<String, String> removeRepetitionFromMap(Map<String, String> map) {
		Set<Entry<String, String>> set = map.entrySet();

		List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(set);

		Collections.sort(list, new Comparator<Entry<String, String>>() {
			@Override
			public int compare(Entry<String, String> entry1, Entry<String, String> entry2) {
				return Integer.valueOf(entry1.getValue().hashCode()) - Integer.valueOf(entry2.getValue().hashCode());
			}
		});

		// list.size() is dynamic change
		for (int index = 0; index < list.size(); index++) {
			String key = list.get(index).getKey();
			String value = http://www.mamicode.com/list.get(index).getValue();" --> " + value);
		}
	}

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("A", "1");
		map.put("B", "2");
		map.put("C", "2");
		map.put("D", "3");
		map.put("E", "3");

		Map<String, String> new_map = UniqueMap.removeRepetitionFromMap(map);

		// new_sort_map is what we want
		Map<String, String> new_sort_map = UniqueMap.transferToSortedMap(new_map);

		// Print new_sort_map
		UniqueMap.printMap(new_sort_map);
	}
}


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