Java HashMap排序
2015-12-22 22:33
423 查看
HashMap排序可以分为按键排序与按值排序两种,实现思路是先转为List容器,再重写比较函数,调用java内置排序算法即可。
示例代码如下(使用时根据需要修改map容器类型):
按键排序结果:
示例代码如下(使用时根据需要修改map容器类型):
HashMap<String, Double> map = new HashMap<String, Double>(); map.put("key1", Math.random() * 100); map.put("key4", Math.random() * 100); map.put("key3", Math.random() * 100); map.put("key5", Math.random() * 100); map.put("key2", Math.random() * 100); List<Map.Entry<String, Double>> mapList = new ArrayList<Map.Entry<String, Double>>(map.entrySet()); // 排序前打印 System.out.println("排序前"); for (Map.Entry<String, Double> entry : mapList) { System.out.println(entry.toString()); } System.out.println(); Collections.sort(mapList, new Comparator<Map.Entry<String, Double>>() { public int compare(Map.Entry<String, Double> obj1, Map.Entry<String, Double> obj2) { // 请使用内置比较函数, 否则可能会报错, 违反使用约定 // 具体要满足交换律, 即返回值compare(x, y)与compare(y, x)应一致 return obj1.getValue().compareTo(obj2.getValue()); // 比较map值 // return obj1.getKey().compareTo(obj2.getKey()); // 比较map键 } }); // 排序后打印 System.out.println("排序后"); for (Map.Entry<String, Double> entry : mapList) { System.out.println(entry.toString()); }按值排序结果:
排序前 key1=40.189446938991416 key2=97.14547760681302 key5=39.86978413432413 key3=44.246717054280374 key4=65.19003398617575 排序后 key5=39.86978413432413 key1=40.189446938991416 key3=44.246717054280374 key4=65.19003398617575 key2=97.14547760681302
按键排序结果:
排序前 key1=71.17675919899192 key2=88.06383506265738 key5=17.37417655482928 key3=1.89149771013285 key4=72.09130459451002 排序后 key1=71.17675919899192 key2=88.06383506265738 key3=1.89149771013285 key4=72.09130459451002 key5=17.37417655482928
相关文章推荐
- Java HashMap排序
- Java HashMap排序
- Java HashMap排序
- Java HashMap排序
- Java HashMap排序
- Java HashMap排序
- Java HashMap排序
- 从头认识java-13.15 使用泛型时出现的问题(2)-实现参数化接口与重载
- 有关android 导入eclipse里的library包的相关事宜
- ReentrantLock源码分析(JDK 1.7)
- java项目怎么加包而不是引用
- 理解Java的类和对象
- 40个Java多线程问题总结(优就业JAVA分享)
- java——反射
- 菜鸟猿大战Java之集合框架系列(四)
- 从头认识java-13.15 使用泛型时出现的问题(1)-泛型不能使用基础类型
- 输出 java.library.path
- 安卓学习记录-java-day5
- Spring基础
- JAVA中堆栈和内存分配