Replace Expression Lambda with Method Reference

Properties

Property Value
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.

Requirement & Tags

Requirements

Java 8

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);

Automatic Application of This Rule

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