== 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

[source,java,diff-id=1,diff-type=noncompliant]
----
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

[source,java,diff-id=1,diff-type=compliant]
----
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

* https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html[Method References - The Java™ Tutorials]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Replace this lambda with a method reference. [(sonar.java.source not set. Assuming 8 or greater.)]


'''
== Comments And Links
(visible only on this page)

=== on 21 Nov 2024, 16:48:00 Alban Auzeill wrote:
[test-code-support-investigation-for-java] Decision for scope: Main -> All.

=== is duplicated by: S2212

=== on 26 Feb 2014, 12:19:41 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-465

endif::env-github,rspecator-view[]
