# Replace Expression Lambda with Method Reference

# Properties

Property Value
Rule ID LambdaToMethodReference
First seen in jSparrow version 2.0.0
Minimum Java version 8
Remediation cost 2 min
Links S1612

# Description

This rule simplifies expression lambdas by using method reference. The rule can only be applied if the parameters of the lambda expression and the method match.

# Benefits

Improves the readability by removing unnecessary syntax.

# Code Changes

# Reference to static method

Pre

 Collections.sort(personList, (Person a, Person b) -> Person.compareByAge(a, b));

Post

Collections.sort(personList, Person::compareByAge);

# Reference to instance method

Pre

Collections.sort(personList, (Person a, Person b) -> comparisonProvider.compareByName(a, b));

Post

Collections.sort(personList, comparisonProvider::compareByName);

# Reference to local method

Pre

personList.forEach((Person person) -> doSomething(person));

Post

personList.forEach(this::doSomething);

# Reference to instance method of arbitrary type

Pre

Arrays.sort(stringArray, (String a, String b) -> a.compareToIgnoreCase(b));

Post

Arrays.sort(stringArray, String::compareToIgnoreCase);

# Reference to constructor

Pre

Set<Person> persSet = transferElements(personList, () -> new HashSet<>());

Post

Set<Person> persSet = transferElements(personList, HashSet::new);

# Bytecode JDK 1.8

Pre

public void original(List<String> values) {
    values.forEach(value -> consume(value));
}
 0 aload_1
 1 aload_0
 2 invokedynamic #2 <accept, BootstrapMethods #0>
 7 invokeinterface #3 <java/util/List.forEach> count 2
12 return

Post

public void transformed(List<String> values) {
    values.forEach(this::consume);
}
 0 aload_1
 1 aload_0
 2 invokedynamic #4 <accept, BootstrapMethods #1>
 7 invokeinterface #3 <java/util/List.forEach> count 2
12 return

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow versions:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊