priorityqueue< map.entry< string,integer>>不接受来自我的Map的entry对象

iq0todco  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(463)

我有一个字符串的arraylist,这些字符串作为键放入Map中。该Map的值是字符串出现的频率。
我想读取20个最频繁的字符串,所以我使用的是priorityqueue,它实现了max堆结构。
尽管优先级队列元素的参数类型看起来是正确的,但我无法将其添加到优先级队列。

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)
exdqitrt

exdqitrt1#

你还没有指定 Comparator<Map.Entry<String, Integer>> 当你建造 PriorityQueue . 你必须这样做。
也许你想要的只是

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

相关问题