Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Map.Entry getValue() is returning an Object even though it should be an Integer

I’m trying to solve https://leetcode.com/problems/top-k-frequent-elements/ and have decided to use a PriorityQueue to store values of Map.Entry<Integer, Integer>. I have the following code:

class Solution {
    public int[] topKFrequent(int[] nums, int k) {

        HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();

        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(k, (Map.Entry e1, Map.Entry e2) -> {
            Integer e1Val = e1.getValue();
            Integer e2Val = e2.getValue();
            return e1Val - e2Val;
        });

        for (var entry : countMap.entrySet()) {
            pq.add(entry);
        }

        return null;
        
    }
}

I am trying to have a custom comparator in my PriorityQueue which uses the value of the Map.Entry<Integer, Integer> to do the sorting.

However, I get the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Line 15: error: incompatible types: Object cannot be converted to Integer
            Integer e1Val = e1.getValue();
                                       ^
Line 16: error: incompatible types: Object cannot be converted to Integer
            Integer e2Val = e2.getValue();
                                       ^
2 errors

Why is it saying that my Map.Entry getValue() is an Object when it is actually an Integer?

>Solution :

You’re using raw Map.Entry for e1 and e2. Change it like,

PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(k,
        (Map.Entry<Integer, Integer> e1, Map.Entry<Integer, Integer> e2) -> {
            Integer e1Val = e1.getValue();
            Integer e2Val = e2.getValue();
            return e1Val - e2Val;
        });

Or just remove the type hint for e1 and e2.

PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(k, (e1, e2) -> {
    Integer e1Val = e1.getValue();
    Integer e2Val = e2.getValue();
    return e1Val - e2Val;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading