Wednesday, 20 January 2021

Java11: Local variable syntax for Lambda Expressions

From Java11 onwards 'var' identifier can be used in implicitly typed Lambda expressions.

 

Lambda Expression

Lambda expressions is a new feature included in Java SE 8. Lambda Expressions provide a way to represent functional interface using an expression.

 

A Functional interface is the one which has only one abstract method. The method declared in functional interface must not a public member of Object class.

 

Let’s try to implement all Arithmetic operations using Anonymous classes first and see How can we modify the same program using Lambda Expressions.

 

public interface Operation {

    int operation(int var1, int var2);

}

 

Addition operation can be implemented using anonymous class like below.

 

Operation add1 = new Operation() {

         public int operation(int a, int b) {

                  return (a + b);

         }

};

 

You can implement same addition operation using lambda expression like below.

 

Operation add2 = (int a, int b) -> {

         return (a + b);

};

                  (OR)

Operation add3 = (a, b) -> {

         return (a + b);

};

 

From Java11 onwards, 'var' is allowed when declaring the formal parameters of implicitly typed lambda expressions.

 

Operation add4 = (var a, var b) -> {

         return (a + b);

};

 

Find the below working application.

 

App.java

package com.sample.app;

public class App {

	public static interface Operation {
		int operation(int var1, int var2);
	}

	public static void main(String args[]) {
		Operation add1 = new Operation() {
			public int operation(int a, int b) {
				return (a + b);
			}
		};

		Operation add2 = (int a, int b) -> {
			return (a + b);
		};

		Operation add3 = (a, b) -> {
			return (a + b);
		};

		Operation add4 = (var a, var b) -> {
			return (a + b);
		};

		int x = 20, y = 30;

		int result1 = add1.operation(x, y);
		int result2 = add2.operation(x, y);
		int result3 = add3.operation(x, y);
		int result4 = add4.operation(x, y);

		System.out.println("Sum of 10 and 20 is : " + result1);
		System.out.println("Sum of 10 and 20 is : " + result2);
		System.out.println("Sum of 10 and 20 is : " + result3);
		System.out.println("Sum of 10 and 20 is : " + result4);
	}
}

 

Output

Sum of 10 and 20 is : 50
Sum of 10 and 20 is : 50
Sum of 10 and 20 is : 50
Sum of 10 and 20 is : 50

 

Reference

https://openjdk.java.net/jeps/323

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment