逆序(从大到小排序):
public static <T> LinkedHashMap<T, Integer> sortByValue2(Map<T, Integer> hm) {
// HashMap的entry放到List中
List<Map.Entry<T, Integer>> list =
new LinkedList<Map.Entry<T, Integer>>(hm.entrySet());
// 对List按entry的value排序
Collections.sort(list, new Comparator<Map.Entry<T, Integer>>() {
public int compare(Map.Entry<T, Integer> o1,
Map.Entry<T, Integer> o2) {
return -((o1.getValue()).compareTo(o2.getValue()));
}
});
LinkedHashMap<T, Integer> res = new LinkedHashMap<>();
for (Map.Entry<T, Integer> aa : list) {
res.put(aa.getKey(), aa.getValue());
}
return res;
}
正序(从小到大排序),和逆序相比把,负号改成正号即可:
public static <T> LinkedHashMap<T, Integer> sortByValue2(Map<T, Integer> hm) {
// HashMap的entry放到List中
List<Map.Entry<T, Integer>> list =
new LinkedList<Map.Entry<T, Integer>>(hm.entrySet());
// 对List按entry的value排序
Collections.sort(list, new Comparator<Map.Entry<T, Integer>>() {
public int compare(Map.Entry<T, Integer> o1,
Map.Entry<T, Integer> o2) {
return ((o1.getValue()).compareTo(o2.getValue()));
}
});
LinkedHashMap<T, Integer> res = new LinkedHashMap<>();
for (Map.Entry<T, Integer> aa : list) {
res.put(aa.getKey(), aa.getValue());
}
return res;
}