Why is this an issue?
Method or constructor references are more readable than lambda expressions in many situations, and may therefore be preferred.
However, method references are sometimes less concise than lambdas. In such cases, it might be preferrable to keep the lambda expression for better
readability. Therefore, this rule only raises issues on lambda expressions where the replacement method reference is shorter.
This rule is automatically disabled when the project’s sonar.java.source
is lower than 8
, as lambda expressions were
introduced in Java 8.
How to fix it
Refer to the called method by its reference instead of wrapping it in a lambda expression.
For instance:
-
null
checks can be replaced with references to Objects::isNull
and Objects::nonNull
- Casts can be replaced with
SomeClass.class::cast
-
instanceof
can be replaced with SomeClass.class::isInstance
Code examples
Noncompliant code example
class A {
void process(List<A> list) {
list.stream()
.filter(myListValue -> myListValue instanceof B) // Noncompliant
.map(listValueToMap -> (B) listValueToMap) // Noncompliant
.map(bValueToMap -> bValueToMap.<String>getObject()) // Noncompliant
.forEach(o -> System.out.println(o)); // Noncompliant
}
}
class B extends A {
<T> T getObject() {
return null;
}
}
Compliant solution
class A {
void process(List<A> list) {
list.stream()
.filter(B.class::isInstance) // Compliant
.map(B.class::cast) // Compliant
.map(B::<String>getObject) // Compliant
.forEach(System.out::println); // Compliant
}
}
class B extends A {
<T> T getObject() {
return null;
}
}
Resources