SONAR: Replace this lambda with a method reference(SONAR:将此 lambda 替换为方法引用)
问题描述
Sonar 告诉我用方法引用替换这个 lambda"
Sonar tells me "Replace this lambda with a method reference"
public class MyClass {
private List<SomeValue> createSomeValues(List<Anything> anyList) {
return anyList //
.stream() //
.map(anything -> createSomeValue(anything)) //
.collect(Collectors.toList());
}
private SomeValue createSomeValue(Anything anything) {
StatusId statusId = statusId.fromId(anything.getStatus().getStatusId());
return new SomeValue(anything.getExternId(), statusId);
}
}
这可能吗?我尝试了几件事,比如
Is this possible here? I tried several things, like
.map(MyClass::createSomeValue) //
但是我需要将方法更改为静态.而且我不是静态方法的忠实粉丝.
but I need to change the method to static then. And I am not a big fan of static methods.
SonarQube 的解释是:
Explanation of SonarQube is:
方法/构造函数引用比使用 lambda 更紧凑和可读,因此是首选.
Method/constructor references are more compact and readable than using lambdas, and are therefore preferred.
推荐答案
是的,你可以使用 this::createSomeValue
:
private List<SomeValue> createSomeValues(List<Anything> anyList) {
return anyList //
.stream() //
.map(this::createSomeValue) //
.collect(Collectors.toList());
}
这种方法参考称为"对特定对象的实例方法的引用".在这种情况下,您指的是实例 this
的方法 createSomeValue
.
This kind of method reference is called "Reference to an instance method of a particular object". In this case, you are referring to the method createSomeValue
of the instance this
.
使用 lambda 表达式是否更好"是一个见仁见智的问题.但是,您可以参考 this answer/brian-goetz">Brian Goetz 解释了为什么首先在语言中添加方法引用.
Whether it is "better" or not that using a lambda expression is a matter of opinion. However, you can refer to this answer written by Brian Goetz that explains why method-references were added in the language in the first place.
这篇关于SONAR:将此 lambda 替换为方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SONAR:将此 lambda 替换为方法引用


基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01