Java:HashMap按键值排序
来源:互联网 发布:正规淘宝代刷信誉平台 编辑:程序博客网 时间:2024/05/21 12:47
- HashMap存储每对键和值作为一个Entry
Map<String,Integer> map=new HashMap<String,Integer>();
2.创建一个简单的HashMap,并插入一些键和值。
map.put("张三", 80); map.put("李四", 90); map.put("王五", 70);
3.从HashMap恢复entry集合,如下所示。
Set<Entry<String,Integer>> array=map.entrySet();
4.从上述mapEntries创建LinkedList。我们将排序这个链表来解决顺序问题。我们之所以要使用链表来实现这个目的,是因为在链表中插入元素比数组列表更快。
List<Entry<String,Integer>> list=new LinkedList<Entry<String,Integer>>(array);
5.通过传递链表和自定义比较器来使用Collections.sort()方法排序链表。
Collections.sort(list,new Comparator<Entry<String,Integer>>(){ public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2){ return o1.getValue().compareTo(o2.getValue()); } });
6.得到排序后list之后,可以通过LinkedHashmap存储键和值信息对到新的映射中。由于HashMap不保持顺序,因此我们要使用LinkedHashMap。
完整代码如下:
import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class sortMapByValues { public static void main(String[] args){ Map<String,Integer> map=new HashMap<String,Integer>(); map.put("张三", 80); map.put("李四", 90); map.put("王五", 70); System.out.println("排序之前:"); Set<Entry<String,Integer>> array=map.entrySet(); for(Entry<String,Integer> temp:array){ System.out.println(temp.getKey()+" "+temp.getValue()); } List<Entry<String,Integer>> list=new LinkedList<Entry<String,Integer>>(array); Collections.sort(list,new Comparator<Entry<String,Integer>>(){ public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2){ return o1.getValue().compareTo(o2.getValue()); } }); System.out.println("排序之前:"); for(Entry<String,Integer> temp:list){ System.out.println(temp.getKey()+" "+temp.getValue()); } }}
0 0
- Java:HashMap按键值排序
- Hashmap按键或值排序
- Java面试题:如何对HashMap按键值排序
- HashM-Java面试题:如何对HashMap按键值排序
- Java面试题:如何对HashMap按键值排序
- java hashmap 按键或者按值(升降)排序
- Java HashMap是按键排序的
- HashMap按键排序和按值排序
- HashMap按键排序和按值排序
- 如何对HashMap按键值排序
- 如何对HashMap按键值排序
- 如何对HashMap按键值排序
- Map排序及HashMap按键排序和按值排序
- java HashMap 按值排序
- JAVA HashMap、TreeMap根据value值排序
- JAVA HashMap、TreeMap根据value值排序
- 对HashMap值进行排序java代码
- Java中hashmap按key值排序
- 我是一个线程
- 故障案例,db启动失败,报错mysqld: File binlog not found (Errcode: 2)
- manacher算法总结
- 量子计算磁共振原型机被激光脉冲原型机淘汰
- 通过stringByTrimmingCharactersInSet去除字符串两端的特殊符号
- Java:HashMap按键值排序
- jQuery学习笔记——事件处理
- 广义线性模型(Generalized Linear Models, GLM)
- Android用Gson解析复杂Json
- struts2中重定向到Action代参数
- 前端学习总结(十三)前端模块化
- iOS开发Objective-C编码规范
- 数据挖掘简要介绍
- ubuntu mysql表名大小写区分