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:
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?