Java 8 Lambda Expression

What is a Lambda Expression?
Java Lambda expression are new in JAVA 8.Java lambda expression are java's first step into functional programming.A Java lambda expression is thus a function which can be created without belonging to any class.A lambda expression can be passed around as if it was an object and executed on demand.A lambda expression represents an anonymous function, it comprises of a set of paramater,a lambda operator (->) and function body.

The following are example of Java lambda expression:

1. (x,y) ->x+y;
  - Two numbers x and y returns another number with their summation.
2. (char c) -> == 'y';
  - A character c returns a boolean indicating if it is equal to ‘y’.
3. (int a,int b) -> a * a+b * b
  - Two integers a and b returns another integer with the sum of their squares.
4. () -> 45
  - No parameters returns the integer 45
5. n -> n% 2 !=0;
  - A number n returns a boolean indicating if it is odd.
6.(String s) -> {System.out.println(s);};
  - A string s prints the string to the main output and returns void.
7. -> { System.out.println("Hello Word "); };
  -No parameters prints Hello World! to the main output and returns void.

package com.Java8;

public class Java8Sample {

            public static void main(String args[]) {
                        Java8Sample java8Sample = new Java8Sample();
                        // Type of Declaration add
                        MathOperation add = (int a, int b) -> a + b;
                        // Type of declaration subtraction
                        MathOperation sub = (int a, int b) -> a - b;

                        System.out.println("Addition of the two Number: " + java8Sample.testResult(10, 20, add));
                        System.out.println("subtraction of the two Number: " + java8Sample.testResult(10, 2, sub));

                        //// without parenthesis
                        StringResult result = message -> System.out.println("Hello " + message);
                        result.sayMessage("Working on Lambda Expression");

            }

            interface MathOperation {
                        int operation(int a, int b);
            }

            interface StringResult {
                        void sayMessage(String message);
            }

            public int testResult(int a, int b, MathOperation mathOperation) {
                        return mathOperation.operation(a, b);
            }

}

In Above example we have used various type of lambda expression with interface MethodOperation and then define the implementation of sayMessage

StringResult

No comments: