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, for example

 .map(MyClass::createSomeValue) // 

but I need to change the method to static. And I'm not a big fan of static methods.

SonarQube explanation:

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

+6
source share
1 answer

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 the "Method Reference of an Instance of a Specific Object . " In this case, you are referring to the createSomeValue method of the createSomeValue instance.


Is it "better" or not that using a lambda expression is a matter of opinion. However, you can reference this answer , written by Brian Goetz , which explains why method references were added to the language in the first place.

+10
source

All Articles