PriorityQueue<Map.Entry<String, Integer>> 不接受来自我的地图的条目对象

PriorityQueue<Map.Entry<String, Integer>> not accepting entry objects from my map

我有一个字符串数组列表,这些字符串将作为键放入映射中。该映射的值是字符串出现的频率。

我想读取 20 个最常见的字符串,所以我使用了一个实现最大堆结构的 PriorityQueue。

尽管其元素的参数类型似乎是正确的,但我无法添加到优先级队列中。

static Map<String, Integer> mapGuy = new HashMap<>();
private static PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>();

    public static List<String> head() {

        if (map.size() == 0){
            List<String> res = new ArrayList<>();
            return res;
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            pq.offer(entry);
        }

        List<String> frequentGrams = new ArrayList<>();
        int counter = 0;
        /*
         * the counter this determines that you only add 20 items to frequentGrams
         * 
         * the while loop stops incrementing if there are less than 20 items in the
         * map
         */

        while (!pq.isEmpty() && counter < 20) {
            frequentGrams.add(0, pq.poll().getKey());
            counter++;
        }
        return frequentGrams;
    }

控制台错误信息如下:

Exception in thread "main" java.lang.ClassCastException: class java.util.HashMap$Node 
cannot be cast to class java.lang.Comparable (java.util.HashMap$Node and 
java.lang.Comparable are in module java.base of loader 'bootstrap')

    at java.base/java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:659)

    at java.base/java.util.PriorityQueue.siftUp(PriorityQueue.java:655)

    at java.base/java.util.PriorityQueue.offer(PriorityQueue.java:346)

    at Program3/maps.FrequencyCount.head(FrequencyCount.java:56)

    at Program3/maps.Driver.testHead(Driver.java:48)

    at Program3/maps.Driver.main(Driver.java:25)

您在构造 PriorityQueue 时未指定 Comparator<Map.Entry<String, Integer>>。你必须这样做。

可能你想要的正是

PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
  Comparator.<Map.Entry<String, Integer>>comparingInt(Map.Entry::getValue));