Java_8 New - Lambda ExpressionsIntroduction Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies the development a lot. Syntax A lambda expression is characterised by following syntax.
parameter -> expression body
Following are the important characteristics of a lambda expression.
Create the following java program using any editor of your choice in say C:/> JAVA Java8Tester.java
publicclassJava8Tester{
publicstaticvoid main(String args[]){ Java8Tester tester =newJava8Tester(); //with type declaration MathOperation addition =(int a,int b)-> a + b; //with out type declaration MathOperation subtraction =(a, b)-> a - b; //with return statement along with curly braces MathOperation multiplication =(int a,int b)->{return a * b;}; //without return statement and without curly braces MathOperation division =(int a,int b)-> a / b; System.out.println("10 + 5 = "+ tester.operate(10,5, addition)); System.out.println("10 - 5 = "+ tester.operate(10,5, subtraction)); System.out.println("10 x 5 = "+ tester.operate(10,5, multiplication)); System.out.println("10 / 5 = "+ tester.operate(10,5, division)); //with parenthesis GreetingService greetService1 = message ->System.out.println("Hello "+ message); //without parenthesis GreetingService greetService2 =(message)->System.out.println("Hello "+ message); greetService1.sayMessage("Mahesh"); greetService2.sayMessage("Suresh"); } interfaceMathOperation{ int operation(int a,int b); } interfaceGreetingService{ void sayMessage(String message); } privateint operate(int a,int b,MathOperation mathOperation){ return mathOperation.operation(a, b); } } Verify the result Compile the class using javac compiler as follows
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester to see the result
C:\JAVA>java Java8Tester
See the result.
10 + 5 = 15
10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Mahesh Hello Suresh Following are important points to be considered using above example
In lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression will throw compilation error if variable is assigned a value second time. Scope Example Create the following java program using any editor of your choice in say C:/> JAVA Java8Tester.java
publicclassJava8Tester{
finalstaticString salutation ="Hello! "; publicstaticvoid main(String args[]){ GreetingService greetService1 = message ->System.out.println(salutation + message); greetService1.sayMessage("Mahesh"); } interfaceGreetingService{ void sayMessage(String message); } } Verify the result Compile the class using javac compiler as follows
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester to see the result
C:\JAVA>java Java8Tester
See the result.
Hello! Mahesh
|