如何高效的遍历HashMap 以及对key 进行排序
Map<Integer ,Object> map = new HashMap<Integer,Object>(); for(int i = 0; i<=100;i++){ map.put(i,i); } Iterator<Entry<Integer, Object>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer ,Object> entry = (Entry<Integer ,Object>)iterator.next(); Object key = entry.getKey(); Object value = entry.getValue(); }
第一种:
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
效率高,以后一定要使用此种方式!
第二种:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低,以后尽量少使用!
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
效率高,以后一定要使用此种方式!
第二种:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低,以后尽量少使用!
关于hashmap 按value排序
最近开发中用到了HashMap ,而且想到要利用其value的大小排序。。真是个伤脑筋的问题。
还好,经过查阅各个地方的资料。发现这个下边的代码处理是最简单有效的。代码很少,却达到目的了。
一般我坚持的一个原则的是:能简单处理的,尽量不做复杂工作。
关键代码部分如下:
HashMap map_Data=new HashMap();
map_Data.put("A", "98");
map_Data.put("B", "50");
map_Data.put("C", "50");
map_Data.put("D", "25");
map_Data.put("E", "85");
System.out.println(map_Data);
List<Map.Entry<String, String>> list_Data = new ArrayList<Map.Entry<String, String>>(map_Data.entrySet());
map_Data.put("A", "98");
map_Data.put("B", "50");
map_Data.put("C", "50");
map_Data.put("D", "25");
map_Data.put("E", "85");
System.out.println(map_Data);
List<Map.Entry<String, String>> list_Data = new ArrayList<Map.Entry<String, String>>(map_Data.entrySet());
Collections.sort(list_Data, new Comparator<Map.Entry<String, String>>()
{
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
{
if(o2.getValue()!=null&&o1.getValue()!=null&&o2.getValue().compareTo(o1.getValue())>0){
return 1;
}else{
return -1;
}
}
});
System.out.println(list_Data);
{
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
{
if(o2.getValue()!=null&&o1.getValue()!=null&&o2.getValue().compareTo(o1.getValue())>0){
return 1;
}else{
return -1;
}
}
});
System.out.println(list_Data);
主要的一个知识点在这个Collections.sort(list,Comparator接口实现)地方,而最最重要核心部分是这个Comparator实现
阳光总在风雨后!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理