I have the following code
public static List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> myList = new ArrayList<>();
HashMap<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
if (!map.containsKey(n)) map.put(n, 1);
else map.put(n, map.get(n) + 1);
}
map.entrySet().stream()
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
.limit(k)
.forEach((key, value) -> myList.add(key));
return myList;
}
The forEach
throws the error
Error:(20, 16) java: incompatible types: incompatible parameter types in lambda expression
How can I fix/avoid this error? I'm not quite sure how to apply the answer here that explains the problem: Lambda Expression and generic method
Edit:
Given the answer, the correction is to replace the lambda inside the forEach with
.forEach((entry) -> myList.add(entry.getKey()));