java - TreeMap 自定义比较器

标签 java comparator treemap

所以我想使用带有自定义比较器的 TreeMap 我的键是一个String: id,我的值是一个int: count; 我需要比较计数,作为 TREEMAP 中的值(整数) 所以我有:

在一个类中:

import java.util.*;

public TreeMap<String, Integer> tm = new TreeMap<String, Integer>(new SortIdCount<Integer>());

在另一个类中:

import java.util.Comparator;

public class SortIdCount implements Comparator<Integer>{

    public int compare(Integer count1, Integer count2) {
        return count1.compareTo(count2);
    }

}

在eclipse中显示错误:

The type SortIdCount is not generic; it cannot be parameterized with arguments <Integer>

最佳答案

The type SortIdCount is not generic; it cannot be parameterized with arguments < Integer >

原因:类别 SortIdCount不是 genric 类型,因此您不能传递 parameterized 参数。 行错误:(new SortIdCount<Integer>()

Note : A TreeMap is always sorted based on its keys, however if you want to sort it based on its values then you can build a logic to do this using comparator. Below is a complete code of sorting a TreeMap by values.

按值排序您可以引用下面的代码片段。

import java.util.*;

public class TreeMapDemo {
  //Method for sorting the TreeMap based on values
  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<>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
  }
  public static void main(String args[]) {

    TreeMap<String, Integer> treemap = new TreeMap<>();

    // Put elements to the map
    treemap.put("Key1", 5);
    treemap.put("Key2", 4);
    treemap.put("Key3", 3);
    treemap.put("Key4", 2);
    treemap.put("Key5", 1);

    // Calling the method sortByvalues
    Map sortedMap = sortByValues(treemap);

    // 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 me = (Map.Entry)i.next();
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }
  }
}

有关更多详细信息,请参阅此 answer

关于java - TreeMap 自定义比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998025/

相关文章:

java - 缓存声音并创建它的实例

java - Apache Kafka : 3 partitions, 消费者组中有3个消费者,每个消费者应该是多线程的

java - "Comparison method violates its general contract!"

Java比较器的使用

java - 在比较器中使用字符串时出现错误

java - 获取 TreeMap 的最后 3 个值

java - 如何实现键可变的键值对

java - 是否可以使用 Java 从 AS400 返回对象列表?

java - 准备好的语句未更新记录

java - 添加存储在 TreeMap 中的值