原文: https://beginnersbook.com/2014/07/how-to-sort-a-treemap-by-value-in-java/

    TreeMap总是根据其键进行排序,但是如果你想根据它的值对它进行排序,那么你可以使用比较器来构建一个逻辑。下面是按值排序TreeMap的完整代码。

    1. import java.util.*;
    2. class TreeMapDemo {
    3. //Method for sorting the TreeMap based on values
    4. public static <K, V extends Comparable<V>> Map<K, V>
    5. sortByValues(final Map<K, V> map) {
    6. Comparator<K> valueComparator =
    7. new Comparator<K>() {
    8. public int compare(K k1, K k2) {
    9. int compare =
    10. map.get(k1).compareTo(map.get(k2));
    11. if (compare == 0)
    12. return 1;
    13. else
    14. return compare;
    15. }
    16. };
    17. Map<K, V> sortedByValues =
    18. new TreeMap<K, V>(valueComparator);
    19. sortedByValues.putAll(map);
    20. return sortedByValues;
    21. }
    22. public static void main(String args[]) {
    23. TreeMap<String, String> treemap = new TreeMap<String, String>();
    24. // Put elements to the map
    25. treemap.put("Key1", "Jack");
    26. treemap.put("Key2", "Rick");
    27. treemap.put("Key3", "Kate");
    28. treemap.put("Key4", "Tom");
    29. treemap.put("Key5", "Steve");
    30. // Calling the method sortByvalues
    31. Map sortedMap = sortByValues(treemap);
    32. // Get a set of the entries on the sorted map
    33. Set set = sortedMap.entrySet();
    34. // Get an iterator
    35. Iterator i = set.iterator();
    36. // Display elements
    37. while(i.hasNext()) {
    38. Map.Entry me = (Map.Entry)i.next();
    39. System.out.print(me.getKey() + ": ");
    40. System.out.println(me.getValue());
    41. }
    42. }
    43. }

    输出:

    1. Key1: Jack
    2. Key3: Kate
    3. Key2: Rick
    4. Key5: Steve
    5. Key4: Tom