AR7 AR7 - 2 years ago 203
Java Question

How to avoid "incompatible parameter types in lambda expression" when adding to an ArrayList?

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

.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
.forEach((key, value) -> myList.add(key));

return myList;

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


Given the answer, the correction is to replace the lambda inside the forEach with

.forEach((entry) -> myList.add(entry.getKey()));

Answer Source

You are going about it in a java7-ish way. Modifying external data structures from inside forEach is not how Streams API was meant to be used. Streams API documentation specifically warns against such use in the Side-Effects section of package summary

Instead of appending to list or map from inside forEach, use collect:

import static java.util.Comparator.reverseOrder;
import static java.util.Map.Entry.comparingByValue;
import static;
import static;
import static;

public static List<Integer> topKFrequent(int[] nums, int k) {
    Map<Integer, Long> freq =
            .collect(groupingBy(x->x, counting()));

    return freq.entrySet()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download