首页 > 解决方案 > SonarLint:将此 lambda 替换为方法引用

问题描述

我有一个包含错误列表的集合。我想通过一个键(UUID UserId)对它们进行分组。为此,我从这个答案中复制了代码: https ://stackoverflow.com/a/30202075/4045364

Collection<FilterError> filterErrors = new ArrayList<FilterError>();

// ... some filterErrors get added to the collection ...

return filterErrors.stream().collect(Collectors.groupingBy(w -> w.getUserId()));

Sonar Lint 给我以下错误:

将此 lambda 替换为方法引用。->

我试过的:

基于这些问题:SONAR: Replace this lambda with a method referenceRunable Interface : Replace this lambda with a method reference。(未设置 sonar.java.source。假设为 8 或更大。)

filterErrors.stream().collect(Collectors.groupingBy(this::getUserId()));

基于这个问题:Replace this lambda with method reference 'Objects::nonNull'

filterErrors.stream().collect(Collectors.groupingBy(UUID::getUserId()));

两者都给出错误:

此表达式的目标类型必须是函数式接口

有没有办法解决这个 SonarLint 问题?

标签: javalambdasonarlintmethod-referencesonarlint-eclipse

解决方案


您需要使用流所针对的对象的类名。例子:

List<String> list = ...;
list.stream().collect(Collectors.groupingBy(String::toUpperCase));

所以在你的情况下:

FilterError::getUserId

推荐阅读