Lambda vs Anonymous class in Java 8
What have we learned so far
1. Lambda Expression in Java 8
PART 1 – LAMBDA EXPRESSION IN JAVA 8
Lets compare the difference in between Lambda Expression and Anonymous class.
1. Syntax
Anonymous class:
package com.onlyfullstack; public class LambdaVsAnonymousClass { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Anonymous class"); } }; Thread thread = new Thread(runnable); thread.start(); } }
Lambda:
package com.onlyfullstack; public class LambdaVsAnonymousClass { public static void main(String[] args) { Runnable runnable = () -> System.out.println("Lambda Expression"); Thread thread = new Thread(runnable); thread.start(); } }
2. Implementation
Anonymous class can be used to implement any interface with any number of abstract methods.
Lambda Expression will only work with SAM(Single Abstract Method) types. That is interfaces with only a single abstract method which is also called as Functional Interface. It would fail as soon as your interface contains more than 1 abstract method.
3. Compilation
Anonymous class : Java creates two class files for LambdaVsAnonymousClass java file as
LambdaVsAnonymousClass.class – contains the main program
LambdaVsAnonymousClass$1.class – contains an anonymous class
Lambda Expression: With Lambda expression compiler will create only 1 class file as below.
So Java will create the new class file for each Anonymous class used.
4. Performance
Anonymous classes
Instead of generating direct bytecode for lambda (like proposed anonymous class syntactic sugar approach), compiler declares a recipe (via invokeDynamic instructions) and delegates the real construction approach to runtime.
Lets go to our next tutorial where we will discuss below points :
– Why Lambda Expression only supports final variables in the body?
– How to use the final variable in Lambda Expression?
– What is the effective final variable in Java 8?