Search code examples
javapriority-queue

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


I have an arraylist of strings that are being put into a map as keys. The value of that map is how often/ the frequency that the string occurs.

I want to read off the 20 most frequent strings so I am using a PriorityQueue that is implementing a max heap structure.

I am not able to add to the priority queue despite the argument type for its elements seeming to be correct.

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;
    }

Here is the console error message:

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)

Solution

  • You haven't specified a Comparator<Map.Entry<String, Integer>> when you constructed the PriorityQueue. You must do so.

    Probably what you want is just

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