📜  如何在Java中按值对 TreeMap 进行排序?

📅  最后修改于: 2022-05-13 01:54:53.156000             🧑  作者: Mango

如何在Java中按值对 TreeMap 进行排序?

在Java语言中,TreeMap 总是存储基于键排序的键值对。 TreeMap 实现了 NavigableMap 接口并扩展了 AbstractMap 类。 TreeMap 包含唯一键。

在Java中按值对 TreeMap 进行排序

  • TreeMap 中的元素根据键进行排序。
  • 所以,我们需要发展自己的逻辑来根据价值对其进行排序。我们可以使用比较器类来做到这一点

示例 1:

Java
// Java program to Sort a TreeMap By Value
  
import java.util.*;
class GFG {
     
    public static  > Map
    valueSort(final Map map)
    {
        // Static Method with return type Map and
        // extending comparator class which compares values
        // associated with two keys
        Comparator valueComparator = new Comparator() {
            
                  // 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 sorted = new TreeMap(valueComparator);
        
        sorted.putAll(map);
        
        return sorted;
    }
    
    public static void main(String[] args)
    {
        TreeMap map = new TreeMap();
  
        // 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());
            
        }
    }
}


Java
// Java program to Sort a TreeMap By Value
  
import java.util.*;
  
class GFG {
    // Method for sorting the TreeMap based on values
    public static  > Map
    valueSort(final Map map)
    {
        // Static Method with return type Map and
        // extending comparator class which compares values
        // associated with two keys
        Comparator valueComparator = new Comparator()
        {
              
            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 sorted = new TreeMap(valueComparator);
  
        sorted.putAll(map);
  
        return sorted;
    }
  
    public static void main(String[] args)
  
    {
  
        TreeMap map
            = new TreeMap();
  
        // 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());
        }
    }
}


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

示例 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  > Map
    valueSort(final Map map)
    {
        // Static Method with return type Map and
        // extending comparator class which compares values
        // associated with two keys
        Comparator valueComparator = new Comparator()
        {
              
            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 sorted = new TreeMap(valueComparator);
  
        sorted.putAll(map);
  
        return sorted;
    }
  
    public static void main(String[] args)
  
    {
  
        TreeMap map
            = new TreeMap();
  
        // 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());
        }
    }
}
输出
1: Anshu
3: Chhotu
2: Golu
5: Rajiv
4: Sita