Use Functional Interfaces

Properties

Property Value
First seen in jSparrow version 1.0.0
Minimum Java version 8
Remediation cost 5 min
Links S1604

Description

Converts anonymous inner classes to equivalent lambda expressions.

Benefits

Increases the performance, because lesser objects need to be created. Improves readability because a lot of boilerplate code will be removed.

Requirement & Tags

Requirements

Java 8

Code Changes

Remove anonymous instantiation of functional interface

Pre

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("xx");
    }
};

Post

Runnable runnable = () -> {
    System.out.println("xx");
};

Rename variables if they are present in the scope outside of the inner class

Pre

int a = 5;

AFunctionalInterface foo = new AFunctionalInterface() {
    @Override
    public void method(int a) {
        int b = a;
    }
};

Post

int a = 5;

AFunctionalInterface foo = (int a1) -> {
    int b = a1;
};

Limitations

Variables that are used inside the anonymous class must be effectively final.