# Replace Expression Lambda with Method Reference

# 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.

# Tags

# 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

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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