java哈希表根据value值排序实例源码

java哈希表根据value值排序实例源码:

/**
* 功能:排序并输出
*/
private static void outputRegionStatistics(HashMap<String, Integer> regionMap){
ArrayList<Entry<String, Integer>> mappingList = new ArrayList<Map.Entry<String, Integer>>(regionMap.entrySet());
//通过比较器实现比较排序
Collections.sort(mappingList, new Comparator<Map.Entry<String,Integer>>(){
public int compare(Map.Entry<String,Integer> mapping1,Map.Entry<String,Integer> mapping2){
return mapping1.getValue().compareTo(mapping2.getValue());
}
});
//倒序输出(降序)
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(RESULTPATH));

output.write(“词频\t\t词语\n—————————\n”);
for(int i=mappingList.size()-1; i>=0; i–){
String line = mappingList.get(i).getValue()+”\t\t”+mappingList.get(i).getKey();
System.out.println(line);
output.write(line+”\n”);
}

output.close();
} catch (IOException e) {
e.printStackTrace();
}
}

本代码针对Java语言,传入的参数为待排序的哈希表,程序先通过Collections.sort对该哈希表进行升序排列,然后再通过倒序输出,得到降序序列。

理论上Collections.sort应该也直接有降序排序的方法函数,不过我还没找到具体方法,有了解的同学欢迎指出^_^ 本文链接地址: java哈希表根据value值排序实例源码