java HashMap sorting lt;String,Integergt; . How to sort it?(java HashMap排序lt;String,Integergt;.如何排序?)
问题描述
<块引用>可能的重复:
如何对地图进行排序<键、值>关于 Java 中的值?
在我的项目中,我采用了这样的 HashMap
<块引用>HashMap 度数 = new HashMap();
假设我有:
degree.put("a",5);度.put("b",2);度.put("c",4);度.put("d",2);度.put("e",3);度.put("f",5);<块引用>
现在我必须根据给定的整数值对该列表进行排序
排序后的 HashMap 应该是:
<块引用>{a=5, f=5, c=4, e=4, b=4, d=2}
我该怎么做?
一个 HashMap 是一个 无序 集合.它没有排序顺序.即使是 TreeMap 也会按键排序,而不是按值排序.
如果要按值的排序顺序准备排序列表,则必须创建一个适当的对象,例如 ArrayList<Map.Entry<String,Integer>>,遍历您的 HashMap 并插入所有条目,然后使用排序函数调用 Collections.sort.
Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
In my project, I have taken a HashMap like this
HashMap degree = new HashMap();
Suppose I have:
degree.put("a",5);
degree.put("b",2);
degree.put("c",4);
degree.put("d",2);
degree.put("e",3);
degree.put("f",5);
Now I have to Sort this list according to given Integer values
Sorted HashMap Should be :
{a=5, f=5, c=4, e=4, b=4, d=2}
How I can do this ?
A HashMap is an unordered collection. It has no sort order. Even a TreeMap will sort by key, not value.
If you want to prepare a sorted list by the sort order of the values, you'll have to create an appropriate object, such as an ArrayList<Map.Entry<String,Integer>>, iterate over your HashMap and insert all the entries, and then call Collections.sort with a collation function.
这篇关于java HashMap排序<String,Integer>.如何排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java HashMap排序<String,Integer>.如何排序
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
