主要思路:将待排序Map中的所有元素置于一个列表中,接着使用Collections的一个静态方法 sort(List list, Comparator<? super T> c) 来排序列表,同样是用比较器定义比较规则。排序后的列表中的元素再依次装入Map,为了肯定的保证Map中元素与排序后的List中的元素的顺序一致,使用了LinkedHashMap数据类型。
//Map根据value进行排序
public static Map<String, Integer> valueUpSort(Map<String, Integer> map) {
//map不能为空
if (map == null || map.isEmpty()) {
return null;
}
//定义一个LinkedHashMap
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
//比较器
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
//降序
return o2.getValue().compareTo(o1.getValue());
//升序
// return o2.getValue().compareTo(o1.getValue());
}
});
Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
Map.Entry<String, Integer> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
该博客介绍了如何使用Java对Map按值进行排序,通过将Map转换为List,然后利用Collections.sort()方法配合自定义比较器实现降序排序。排序后,将元素重新装入LinkedHashMap以保持键值对的顺序。这种方法适用于需要保持插入顺序且按特定字段排序的情况。
1997

被折叠的 条评论
为什么被折叠?



