首页 > 代码库 > 删除Map中Value重复的记录,并且只保留Key最小的那条记录

删除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();>