Map 根据value 排序

总是有特殊的需求 ,呵呵 ,一起看看Map 根据value 排序的一个例子吧,还用到了泛型 很不错

此文仅供自己记录笔记。

/**
 * hashmap 根据值排序
 */
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list =
            new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o2.getValue()).compareTo(o1.getValue());
        }
    });
    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

posted @ 2014-12-31 20:31  NPH  阅读(159)  评论(0编辑  收藏  举报