SONAR: Replace this lambda with a method reference

自作多情 提交于 2020-01-23 04:32:20

问题


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.

Explanation of SonarQube is:

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


回答1:


Yes, you can use this::createSomeValue:

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

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.


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.



来源:https://stackoverflow.com/questions/35507937/sonar-replace-this-lambda-with-a-method-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!