能夠先將map中各元素存放在list中,再對list進行排序。list排序,利用Collections.sort()只要重寫compare方法便可。java
下面的代碼實現按照value值的降序排列。ide
public static Map<String, Long> sortMap(Map<String, Long> oldMap) {
ArrayList<Map.Entry<String, Long>> list = new ArrayList<Map.Entry<String, Long>>(oldMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
@Override
public int compare(Entry<java.lang.String, Long> arg0,
Entry<java.lang.String, Long> arg1) {
return (int) (arg1.getValue() - arg0.getValue());
}
});
Map<String, Long> newMap = new LinkedHashMap<String, Long>();
for (int i = 0; i < list.size(); i++) {
newMap.put(list.get(i).getKey(), list.get(i).getValue());
}
return newMap;
} 排序