- public static Map sortMap(Map map) {
- Map oneMap = new LinkedHashMap() ;
- ArrayList<Entry<String, String>> l = new ArrayList<Entry<String, String>>(map.entrySet());
- Collections.sort(l, new Comparator<Object>() {
- public int compare(Object e1, Object e2) {
- int v1 = Integer.parseInt(((Entry<String, String>) e1).getValue().toString());
- int v2 = Integer.parseInt(((Entry) e2).getValue().toString());
- return v2-v1; // 降序 v1-v2升序
- }
- });
- for (Entry<String, String> e : l) {
- oneMap.put(e.getKey(), e.getValue()) ;
- }
- return oneMap ;
- }
public static Map sortMap(Map map) {
Map oneMap = new LinkedHashMap() ;
ArrayList<Entry<String, String>> l = new ArrayList<Entry<String, String>>(map.entrySet());
Collections.sort(l, new Comparator<Object>() {
public int compare(Object e1, Object e2) {
int v1 = Integer.parseInt(((Entry<String, String>) e1).getValue().toString());
int v2 = Integer.parseInt(((Entry) e2).getValue().toString());
return v2-v1; // 降序 v1-v2升序
}
});
for (Entry<String, String> e : l) {
oneMap.put(e.getKey(), e.getValue()) ;
}
return oneMap ;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
本文介绍了一种使用Java实现的Map按值降序排序的方法。通过将Map转换为ArrayList,并利用Collections.sort结合自定义Comparator实现排序,最后将排序后的条目重新放入LinkedHashMap中保持插入顺序。该方法适用于需要根据Map的值进行排序的场景。

1086

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



