HashMap排序可以分为按键排序与按值排序两种,实现思路是先转为List容器,再重写比较函数,调用java内置排序算法即可。
示例代码如下(使用时根据需要修改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