How to Sort a TreeMap by Value in Java with Example

In the last tutorial  I have shared TreeMap iterator example. TreeMap is always sorted based on its keys, in this post we will see how to sort it based on the values. We will sort TreeMap based on values using Comparator.Below is the code for sorting TreeMap by values.


Program for sorting TreeMap by Values in Java



import java.util.*;

 public class TreeMapSortByValue {
    public static void main(String args[]) {
        
    // Declaring a TreeMap of String keys and String values
    TreeMap<String, String> treemap = new TreeMap<String, String>();
    // Add Key-Value pairs to TreeMap
    treemap.put("Key1", "Pear");
    treemap.put("Key2", "Apple");
    treemap.put("Key3", "Orange");
    treemap.put("Key4", "Papaya");
    treemap.put("Key5", "Banana");
    
    //sort treemap by values
    Map sortedMap = sortByValues(treemap);
    // Get Set of entries
    Set set = sortedMap.entrySet();
    // Get iterator
    Iterator it = set.iterator();
    // Show TreeMap elements
    System.out.println("TreeMap contains: ");
    while(it.hasNext()) {
      Map.Entry pair = (Map.Entry)it.next();
      System.out.print("Key is: "+pair.getKey() + " and ");
      System.out.println("Value is: "+pair.getValue());
    }
  }
    
  public static <K, V extends Comparable<V>> Map<K, V> 
  sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator = 
             new Comparator<K>() {
      public int compare(K k1, K k2) {
        int compare = 
              map.get(k1).compareTo(map.get(k2));
        if (compare == 0) 
          return 1;
        else 
          return compare;
      }
    };
 
    Map<K, V> sortedByValues = 
      new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
    }
 }    


Output
TreeMap contains: 
Key is: Key2 and Value is: Apple
Key is: Key5 and Value is: Banana
Key is: Key3 and Value is: Orange
Key is: Key4 and Value is: Papaya
Key is: Key1 and Value is: Pear

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry