Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHow to Sort a TreeMap By Value in Java?

How to Sort a TreeMap By Value in Java?

In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys.

Sorting TreeMap by value in Java

  • The elements in TreeMap are sorted on the basis of keys.
  • So, we need to develop our own logic to sort it on the basis of value. We can do it using comparator class 

Example 1:

Java




// Java program to Sort a TreeMap By Value
  
import java.util.*;
class GFG {
     
    public static <K, V extends Comparable<V> > Map<K, V>
    valueSort(final Map<K, V> map)
    {
        // Static Method with return type Map and
        // extending comparator class which compares values
        // associated with two keys
        Comparator<K> valueComparator = new Comparator<K>() {
            
                  // return comparison results of values of
                  // two keys
                  public int compare(K k1, K k2)
                  {
                      int comp = map.get(k1).compareTo(
                          map.get(k2));
                      if (comp == 0)
                          return 1;
                      else
                          return comp;
                  }
            
              };
        
        // SortedMap created using the comparator
        Map<K, V> sorted = new TreeMap<K, V>(valueComparator);
        
        sorted.putAll(map);
        
        return sorted;
    }
    
    public static void main(String[] args)
    {
        TreeMap<String, Integer> map = new TreeMap<String, Integer>();
  
        // Put elements to the map
        map.put("Anshu", 2);
        map.put("Rajiv", 4);
        map.put("Chhotu", 3);
        map.put("Golu", 5);
        map.put("Sita", 1);
  
        // Calling the method valueSort
        Map sortedMap = valueSort(map);
  
        // Get a set of the entries on the sorted map
        Set set = sortedMap.entrySet();
  
        // Get an iterator
        Iterator i = set.iterator();
  
        // Display elements
        while (i.hasNext()) {
            
            Map.Entry mp = (Map.Entry)i.next();
            System.out.print(mp.getKey() + ": ");
            System.out.println(mp.getValue());
            
        }
    }
}


Output

Sita: 1
Anshu: 2
Chhotu: 3
Rajiv: 4
Golu: 5

Example 2:

Java




// Java program to Sort a TreeMap By Value
  
import java.util.*;
  
class GFG {
    // Method for sorting the TreeMap based on values
    public static <K, V extends Comparable<V> > Map<K, V>
    valueSort(final Map<K, V> map)
    {
        // Static Method with return type Map and
        // extending comparator class which compares values
        // associated with two keys
        Comparator<K> valueComparator = new Comparator<K>()
        {
              
            public int compare(K k1, K k2)
            {
  
                int comp = map.get(k1).compareTo(map.get(k2));
  
                if (comp == 0)
                     return 1;
  
                else
                     return comp;
            }
        };
  
        // SortedMap created using the comparator
        Map<K, V> sorted = new TreeMap<K, V>(valueComparator);
  
        sorted.putAll(map);
  
        return sorted;
    }
  
    public static void main(String[] args)
  
    {
  
        TreeMap<Integer, String> map
            = new TreeMap<Integer, String>();
  
        // Put elements to the map
        map.put(1, "Anshu");
  
        map.put(5, "Rajiv");
  
        map.put(3, "Chhotu");
  
        map.put(2, "Golu");
  
        map.put(4, "Sita");
  
        // Calling the method valueSort
        Map sortedMap = valueSort(map);
  
        // Get a set of the entries on the sorted map
        Set set = sortedMap.entrySet();
  
        // Get an iterator
        Iterator i = set.iterator();
  
        while (i.hasNext())
        {
            Map.Entry mp = (Map.Entry)i.next();
  
            System.out.print(mp.getKey() + ": ");
  
            System.out.println(mp.getValue());
        }
    }
}


Output

1: Anshu
3: Chhotu
2: Golu
5: Rajiv
4: Sita
RELATED ARTICLES

Most Popular

Recent Comments