简体   繁体   English

添加到ArrayList时如何避免“lambda表达式中不兼容的参数类型”?

[英]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);
  }

  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 forEach抛出错误

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 我不太清楚如何在这里应用解释问题的答案: Lambda Expression和泛型方法

Edit: 编辑:

Given the answer, the correction is to replace the lambda inside the forEach with 给出答案,更正是用forEach替换lambda中的lambda

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

entrySet() returns a set of Pair<K, V> . entrySet()返回一组Pair<K, V>

forEach() 's lambda therefore takes a single parameter of that type; forEach()的lambda因此采用该类型的单个参数; not two integer parameters. 不是两个整数参数。

You are going about it in a java7-ish way. 你是以java7-ish的方式进行的。 Modifying external data structures from inside forEach is not how Streams API was meant to be used. forEach内部修改外部数据结构并不是要使用Streams API的方式。 Streams API documentation specifically warns against such use in the Side-Effects section of java.util.stream package summary Streams API文档专门警告java.util.stream包汇总的Side-Effects部分中的此类使用

Instead of appending to list or map from inside forEach , use collect : 使用collect :而不是从forEach内部追加列表或地图。

import static java.util.Comparator.reverseOrder;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;


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

    return freq.entrySet()
            .stream()
            .sorted(comparingByValue(reverseOrder()))
            .limit(k)
            .map(Map.Entry::getKey)
            .collect(toList());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM