Arithmetic Operation Using Lambda Expression

By | August 15, 2017

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of thePerson class.Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:
    p -> p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
  • The arrow token, ->
  • A body, which consists of a single expression or a statement block. This example uses the following expression:
    p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25

    If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

    p -> {
        return p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25;
    }

    A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

    email -> System.out.println(email)

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.

Source : Oracle.docs

Example:

interface calculate
{
    int cal(int a ,int b);
}
public class CALCULATION{

    public static void main(String[] args) {
        calculate add = (a,b)-> a+b;
        System.out.println("Adding 6+4 :"+add.cal(6,4));

        calculate sub = (a,b)-> a-b;
        System.out.println("Sub 10-5 :"+sub.cal(10,5));

        calculate mul = (a,b)-> a*b;
        System.out.println("Mul 5*5 :" +mul.cal(5,5));
    }
}
Output 
Adding 6+4 :10
Sub 10-5 :5
Mul 5*5 :25