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

Gar*_*ett 1 java priority-queue

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

我想读取 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;
    }
Run Code Online (Sandbox Code Playgroud)

这是控制台错误消息:

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)
Run Code Online (Sandbox Code Playgroud)

Lou*_*man 5

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

也许你想要的只是

PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
  Comparator.<Map.Entry<String, Integer>>comparingInt(Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)