Monday, August 9, 2021

Java 8: Lambda Expressions

  • Lambda expression adds functional programming in Java
  • Lambda expression is short and concise way of representing functional interface implementation
  • Lambda expressions are used to pass a behavior (with values) to the function code
  • Though Lambda expressions are similar as that of inner classes they are NOT same in followings
    • Inner classes creates new scope for local variables and refers 'this' to class instance
    • Lambda expression can't hide local variables inside body and refers 'this' to enclosing class instance

Example:

       


package java8.lambda;

public class LambdaDemo {

	public static void main(String[] args) {
		MyFunctionalInterface myFunctionalInterface1 = new MyFunctionalInterface() {
			@Override
			public void add(int a, int b) {
				System.out.println("Sum with Boiler Plate Code is "+ (a+b));
			}
		};
		myFunctionalInterface1.add(3, 4);
		
		MyFunctionalInterface myFunctionalInterface2 = (a,b) -> System.out.println("Sum with Lambda is "+(a+b));
		myFunctionalInterface2.add(5, 2);
	}
}

@FunctionalInterface
interface MyFunctionalInterface{
	abstract void add(int a, int b);
}

Also see, how to handle exception in lambda, here

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...