Thursday, February 23, 2017

Lambdas in Java(1.8) - 3 - Anonymous InnerClass replaced with Lambda



Replace Anonymous inner classes with Lambdas.

A classic situation of using Lambda to replace an anonymous class, with Only one method(a must condition) is the Thread declaration that implements an inner Runnable interface as below:


public class ReplaceAnonymousWithLambda {
public static void main(String[] args) {
//Using Runnable anonymour inner class
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("run() executed from Runnable Anonymous inner class");
}
});
//-----------------(A)
thread.run();

//Using Lambda function as a replacement for the Runnable anoynymous class
thread = new Thread(()->System.out.println("contents as in run() using Lambda exp"));
//-----------------(B)
thread.run();
}

}

No comments:

Post a Comment