Monday, 24 May 2021

Lambda Expression in Java 8

Lambda Expression













Lambda calculus was the big change in Mathematical world which came in 1930s.
Because of this programmers also started using it.

LISP is the 1st lang where lambda expressions came first.
Apart form LISP, C, CPP, PYTHON, SCALA, RUBBY, Objective C

Advantages

  1. To enable functional programming in java
  2. To write more readable, maintainable and concise code
  3. To use APIs very easily and effectively.
  4. To enable parallel processing
Lambda Expressionlambda expressions are a means to create anonymous classes of functional interfaces easily
     1. No Name
     2. No Return Type
     3. No Access Modifier

NOTE : Only use in case of functional interface.


Functional Interface : An interface having only one abstract method is known as Functional Interface.
Example : Runnable , Callable etc.

There are some rules to write lambda expression from which two main important rules are
1. If body is having only one statement then { } braces are optional
2. If passing parameter as an argument then argument type is optional

Example.

public void display(String str){
    System.out.println("Hello "+str);
}
Using lambda
(str)->System.out.println("Hello "+str);
or
str->System.out.println("Hello "+str);
int getValue(){
  return 5;
}
Using lambda
() -> 5
// concatenating two strings, it has 2 string parameters and they are concatenated in lambda body
(String s1, String s2) -> s1+s2;


Below are some example codes using lambda

1. Calculator program
























2. Threading



Scenarios

  1. (int x, int y) -> x+y; or (x, y) -> x + y; which one of these is a valid lambda expression?

    Both of them are valid lambda expressions if used in a correct context.


  2. (int x, y) -> x + y; is this a valid lambda expression?

    You can't have lambda expression where type for only one of the parameter is explicitly declared so this lambda expression is invalid.

No comments:

Post a Comment