對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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM