对Java的Map的Value字段进行排序

  构造TreeMap可以指定Comparator,但是不能对value字段进行排序。如果有需求对Value字段排序,例如map存放的是单词,单词出现次数,怎么按单词次数排序呢?

  可以先将map中的key-value放入list,然后用Collections.sort对list排序,再将排序后的list放入LinkedHashMap,最后返回LinkedHashMap就可以了。LinkedHashMap可是个宝贝,可以通过构造方法制定是按放入的顺序,还是get顺序 排序。LinkedHashMap,稍微修改,可以很容易的实现LRU算法(最近最少使用)。具体的TreeMap 红黑树实现和LinkedHashMap实现还仔细看。

  废话不多说,上代码:

public class MapUtil {
    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 (o1.getValue()).compareTo(o2.getValue());
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

Java 7 Version

    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.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

java 8 version

    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Entry<K, V>> st = map.entrySet().stream();

        st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));

        return result;
    }

java 8 版本的代码好短啊 ~

以后做个工具包,像这样的排序直接用工具包使用就可以了。

参考资料:http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java 

posted @ 2014-09-20 17:33  柳qing  阅读(18567)  评论(0编辑  收藏  举报