Sorting HashMap by value using a TreeMap and Comparator

前端 未结 3 656
离开以前
离开以前 2021-01-29 00:48

Im using the following code to create a hashmap and then sort the values in the hashmap by using a treemap and a comparator. However, the output is rather unexpected. So any th

3条回答
  •  独厮守ぢ
    2021-01-29 01:39

    The Java Doc of TreeMap clearly states that:

    A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys

    we should not violate this rule by using TreeMap to sort by values.

    However to sort by values, we can do the following:

    1. Create a LinkedList of entries of the map
    2. using Collection.sort to sort the entries
    3. Inserting the sorted entries to a LinkedHashMap: keeps the keys in the order they are inserted, which is currently sorted on natural ordering.
    4. Return the LinkedHashMap as the sorted map.

       public static  Map sortByValues(Map map){
          List> entries = new LinkedList>(map.entrySet());
      
          Collections.sort(entries, new Comparator>() {
      
              @Override
              public int compare(Entry o1, Entry o2) {
                  return o1.getValue().compareTo(o2.getValue());
              }
          });
      
      
          Map sortedMap = new LinkedHashMap();
      
          for(Map.Entry entry: entries){
              sortedMap.put(entry.getKey(), entry.getValue());
          }
      
          return sortedMap;
      }
      
      }
      

    Reference: Sorting Map by value

提交回复
热议问题