首页 > 代码库 > 【方法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最小的那条记录
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。