Lambda Expression

 

A lambda expression is an anonymous method. This anonymous method is not executed on its own. Instead, it is used to implement a method defined by a functional interface. A functional interface is an interface that contains one and only one abstract method which typically represents a single action.

These are characteristics of a lambda expression:

  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
(String a, String b) -> a+" "+b;
// same as
(a, b) -> a+" "+b;
  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
a -> a;
// same as
(a) -> a;
  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
a -> a;
// same as
a -> {return a;};
  • When there are more than one statements, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.
  • A lambda expression can be passed around as if it was an object and executed on demand.
  • Enable to treat functionality as a method argument, or code as data.
public class LambdaTest 
{ 
	interface Operator 
	{ 
		int operation(int a, int b); 
	} 

	public int operate(int a, int b, Operator op) 
	{ 
		return op.operation(a, b); 
	} 

	public static void main(String args[]) 
	{ 
		Operator add = (int x, int y) -> x + y; 

		LambdaTest test = new LambdaTest(); 

		System.out.println("Addition is " + 
						test.operate(6, 3, add)); 

	
	} 
} 

Lambda expressions are used primarily to define inline implementation of a functional interface.

Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

@FunctionalInterface annotation

@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation.

@FunctionalInterface
public interface Operator {
	int operation(int a, int b);

	// can have static methods
	static String sayHi(String name) {
		return name;
	}
}

Very often, lambda expressions just call methods which are already implemented elsewhere. You can use method references. This is not always shorter, but it makes the code more readable.

a -> a.toLowerCase();
// same as
String::toLowerCase;

Benefits of using Lambda expression

  • Code reuse. The ability to reuse anonymous inner class code is muted, as there’s not way to invoke an it from outside of the code in which it is defined.
  • Readability. No more anonymous inner class. Anonymous inner class can be ugly and not readable.
  • Variables defined outside of an inner class do not employ the traditional rules pertaining to block scope within a Java class.
  • Less boilerplate code. JAR file size reductions.
  •  
Integer[] numbers = {2, 54, 20, 1};
		
Arrays.sort(numbers, new Comparator<Integer>() {
	@Override
	public int compare(Integer a, Integer b) {
		return a - b;
	}
});
		
System.out.println(Arrays.toString(numbers));

How about this version which is much cleaner and more readable.

Integer[] numbers = {2, 54, 20, 1};

Arrays.sort(numbers, (a, b) -> a-b);
		
System.out.println(Arrays.toString(numbers));

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *