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.
To summarize: If the purpose of the lambda expression is solely to pass a parameter to an instance method, then you may replace it with a method reference on the instance. If the pass-through is to a static method, then you may replace it with a method reference on the class.
You can't replace the lambda input -> getValueProvider(). apply(input). getValue() with a method reference without changing the semantics. A method reference replace a single method invocation, so it can't simply replace a lambda expression consisting of more than one method invocation.
Lambda expression is an anonymous method (method without a name) that has used to provide the inline implementation of a method defined by the functional interface while a method reference is similar to a lambda expression that refers a method without executing it.
To convert an anonymous method to a lambda expression Move to the anonymous method you want to convert. From the Refactor menu of the VisualAid choose To Lambda. Telerik® JustCode™ will replace the anonymous method with a lambda expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With