SONAR:用方法引用替换此 lambda

SONAR: Replace this lambda with a method reference

声纳告诉我"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);
    }

}

这里可以吗?我尝试了几件事,比如

.map(MyClass::createSomeValue) //

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

SonarQube 的解释是:

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());
}

这种method reference is called "Reference to an instance method of a particular object"。在这种情况下,您指的是实例 this.

的方法 createSomeValue

是否"better"使用lambda表达式见仁见智。但是,您可以参考 this answer written by Brian Goetz,它解释了为什么首先在语言中添加方法引用。