Map去重,去重value相同的元素,保留key最小的那个值
Map<Integer,String>,Integer代表时间撮,String代表文本信息
去重函数:就是删除Map中value相同的元素,只保留key最小的那个元素
public static Map<Integer,String> RemoveRepFromMap(Map<Integer,String> map){
Set<Entry<Integer,String>> set = map.entrySet();
List<Entry<Integer,String>> list = new ArrayList<Entry<Integer,String>>(set);
Collections.sort(list,new Comparator<Entry<Integer,String>>(){
//重载compare函数 对list集合进行排序,根据value值进行排序,
public int compare(Entry<Integer,String> entry1,Entry<Integer,String> entry2){
return Integer.valueOf(entry1.getValue().hashCode()-entry2.getValue().hashCode());
}
});
for(int i=0;i<list.size();i++){//删除重复的元素
Integer key = list.get(i).getKey();
String value = list.get(i).getValue();
int j=i+1;//map中的下一个
if(j<list.size()){
Integer next_key = list.get(j).getKey();
String next_value = list.get(j).getValue();
if(value == next_value){
if(key.hashCode() < next_key.hashCode()){map.remove(next_key);list.remove(j);
}else{
map.remove(key);list.remove(i);
}
i--;
}
}
return map;
}
Map<Integer,String>首先的特性就是:键key如果相同,将会把原来的key进行覆盖掉的,所以key一定不会重复
几个函数的作用说明:
Map.Entry
表示单个映射关系即一个key+value
entrySet()方法
返回此映射中包含的映射关系的 set 视图集合,其实说白了就是 多个 key+value 的集合,
解释下这里面的set,只有当key和value都一一对应相同的时候,才不会被重复计算【而这种情况根本就不会存到map里面去,因为他会覆盖原来的key】,如果key不同,键相同,依然是在entrySet里面的
最新文章
- Mac 词典工具推荐:Youdao Alfred Workflow(可同步单词本)
- Windows下好用到必须开机自启的小工具
- NET基础(1):类型基础
- JavaWeb工作原理
- 使用Bootstrap-Table 遇到的问题
- javascript工具--控制台详解(转自 阮一峰博客)
- FZU2236 第十四个目标 dp+树状数组优化
- php配置虚拟主机的配置步骤(hosts、httpd.conf、vhosts.conf)1.配置本地的dns文件2.配置apache的主配置文件3.配置Apache的虚拟主机
- HDU - 2290 Find the Path(最短路)
- cocoapod升级版本
- JS为网页添加文字水印【原创】
- batの磕磕碰碰
- linux取IP的几个方法
- light1370 欧拉函数打表
- PAT 甲级 1027 Colors in Mars (20 分)
- 2018-2019-2 《网络对抗技术》Exp0 Kali安装 Week1 20165318
- WIFI底座
- STL中实现 iterator trail 的编程技巧
- topcoder srm 320 div1
- Fragment----静态创建碎片
热门文章
- DataOps Reading Notes
- 【java异常】Expected one result (or null) to be returned by selectOne(), but found: 63
- LCD12864
- Ubuntu-tools安装
- 直接插入排序与缩小增量插入排序(希尔排序ShellSort)
- hive基础知识五
- scp 文件 : /目录: Permission denied
- 【Gamma】Scrum Meeting 10
- MySQL5.7调优参数
- Python OpenCV4获取轮廓最大内切圆和外接圆