有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SONAR:用方法引用替换此lambda

Sonar告诉我“用方法引用替换这个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);
    }

}

这里可能吗?我试过几种方法,比如

.map(MyClass::createSomeValue) //

但是我需要将方法更改为static。我不太喜欢静态方法

SonarQube的解释如下:

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


共 (1) 个答案

  1. # 1 楼答案

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

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

    这种method reference被称为"Reference to an instance method of a particular object"。在本例中,您引用的是实例this的方法createSomeValue


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