简体   繁体   中英

SONAR: Replace this lambda with a method reference

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM