java SONAR:用方法引用替换这个 lambda

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35507937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:12:05  来源:igfitidea点击:

SONAR: Replace this lambda with a method reference

javalambdajava-8sonarqubemethod-reference

提问by Chris311

Sonar tells me "Replace this lambda with a method reference"

声纳告诉我“用方法引用替换这个 lambda”

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.

但我需要将方法更改为静态。而且我不是静态方法的忠实粉丝。

Explanation of SonarQube is:

SonarQube 的解释是:

Method/constructor references are more compact and readable than using lambdas, and are therefore preferred.

方法/构造函数引用比使用 lambda 更紧凑和可读,因此是首选。

回答by Tunaki

Yes, you can use this::createSomeValue:

是的,您可以使用this::createSomeValue

private List<SomeValue> createSomeValues(List<Anything> anyList) {
    return anyList //
            .stream() //
            .map(this::createSomeValue) //
            .collect(Collectors.toList());
}

This kind of method referenceis called "Reference to an instance method of a particular object". In this case, you are referring to the method createSomeValueof the instance this.

这种方法引用称为“对特定对象的实例方法的引用”。在这种情况下,您指createSomeValue的是实例的方法this



Whether it is "better" or not that using a lambda expression is a matter of opinion. However, you can refer to this answerwritten by Brian Goetzthat explains why method-references were added in the language in the first place.

使用 lambda 表达式是否“更好”是一个见仁见智的问题。但是,您可以参考Brian Goetz写的这个答案,它解释了为什么首先在语言中添加了方法引用。