Tuesday, March 1, 2016

Lamda expression vs Anonymous class in java

Lamda expression are anonymous methods, which can be assigned to a variable, passed as an argument or returned as a value of function call.

Lamda expression in java 8 comes as a big relief from writing the boiler plate code needed to implement single method interfaces like comparable, comparator, runnable or callable etc. For writing such methods using anonymous class it use to take minimum six to seven lines of code. The same can be written in a single line while using Lamda expression.

In the following example, we are trying to print 'Salil Verma' using thread. we can notice that Lamda expression is very concise and anonymous class contains boiler plate code.

Anonymous class approach -

public class ThreadAnonymousClassExample {
   
 public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Salil Verma");
            }
        };
        new Thread(runnable).start();
    }
}

Lamda expression approach -

public class ThreadLamdaExample {
   
 public static void main(String[] args) {
        new Thread(()->System.out.println("Salil Verma")).start();
    }
}

Although Lamda expression looks very handy and concise in writing, it has got limitations. This expression can be used only on the situations where we are using single method interface. On situations where interface or abstract class has got more than one methods, Anonymous class is the way to go.

In short, Lamda expression should be preferred over anonymous class where we are implementing single method interface otherwise anonymous class is the way to go.

No comments:

Post a Comment