SONAR: Replace this lambda with a method reference

Chris311 picture Chris311 · Feb 19, 2016 · Viewed 13.7k times · Source

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.

Answer

Tunaki picture Tunaki · Feb 19, 2016

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.