Now the lambda expressions are also introduced in JAVA 8 and it is praised as the biggest attribute of Java 8. These lambda expressions make functional programming smooth and clarify the upgradation path a lot.
The lambda expression is identified by the following Syntax:
Below are the important characteristics of a lambda expression.
You have to create the below given Java Program by using any editor of your choice in, say C:\> JAVA.
Java8Tester.java
public class Java8Tester { public static void main(String args[]) { Java8Tester tester = new Java8Tester(); //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)); //without parenthesis GreetingService greetService1 = message -> System.out.println("Hello " + message); //with parenthesis GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Mahesh"); greetService2.sayMessage("Suresh"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation) { return mathOperation.operation(a, b); } }
Verify Your Result
Assemble the class using javac compiler as follows-
C:\JAVA>javac Java8Tester.java
Now it's time to Run the Java8 tester as given below-
C:\JAVA>java Java8Tester
Your output should be like this:-
10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Mahesh Hello Suresh
Following are the details to be considered in the above example:
Using lambda expression, you'll ask any final variable or effectively final variable (which is assigned only once). Sometimes Lambda expressions direct a compilation error, if a variable is assigned a value the second time.
Scope Example
Create the subsequent Java program using any editor of your choice in, say, C:\> JAVA
Java8Tester.java
public class Java8Tester { final static String salutation = "Hello! "; public static void main(String args[]) { GreetingService greetService1 = message -> System.out.println(salutation + message); greetService1.sayMessage("Mahesh"); } interface GreetingService { void sayMessage(String message); } }
Confirm the Result
Assemble the class using the javac compiler as given below-
C:\JAVA>javac Java8Tester.java
Now you have to run the Java8Tester same as given below:
C:\JAVA>java Java8Tester
Your output must look like this:
Hello! Mahesh