java map去除几条记录_【方法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 transferToSortedMap(Map 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 sort_map = new TreeMap(new Comparator() {

@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 exchangeMap(Map map) {

Map exchange_map = new TreeMap();

for (String key : map.keySet()) {

String value = map.get(key);

exchange_map.put(value, key);

}

return exchange_map;

}

// Print Map

public static void printMap(Map map) {

Iterator> iterator = map.entrySet().iterator();

while (iterator.hasNext()) {

Entry entry = iterator.next();

String key = entry.getKey();

String value = entry.getValue();

System.out.println(key + " --> " + value);

}

}

public static void main(String[] args) {

Map map = new HashMap();

map.put("A", "1");

map.put("C", "3");

map.put("D", "2");

map.put("B", "3");

map.put("E", "3");

// Sort Map by descending order

// Note: Sort according to descending, because retain the smaller Key's record when exchanging Map's Key and Value

Map sort_map = UniqueMap1.transferToSortedMap(map);

// Exchange Key and Value for overlapping repetition record

Map exchange_map = UniqueMap1.exchangeMap(sort_map);

// Exchange Map for recovering Key and Value, this Map is what we want

exchange_map = UniqueMap1.exchangeMap(exchange_map);

// Print Map

UniqueMap1.printMap(exchange_map);

}

}

原文:http://blog.csdn.net/three_man/article/details/33314053

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值