Lambda Expressions

Lambda expression is a new and important feature of Java which was made available in Java SE 8. It basically provides a way to represent one method interface using an expression. In addition, it helps to iterate, filter, and extract data from a collection.

  • The Lambda expression helps to provide the implementation of an interface that has a functional interface(An interface with single abstract method).
  • In addition, the body of a lambda expression can contain zero, one or more statements.
  • However, there is no need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • If a single statement is present, curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.
  • If there is more than one statement present, then these must be enclosed in curly brackets (a code block). In addition to this, the return type of the anonymous function is the same as the type of the value that is returned within the code block, or void if nothing is returned.

Syntax

lambda operator -> body or (Argument list) arrowToken {body}
where lambda operator can be:

  • For Zero parameter – () -> System.out.println(“Zero param lambda”);
  • For One parameter – (p) -> System.out.println(“One param lambda: ” + p);
  • For Multiple parameters – (p1, p2) -> System.out.println(“Multiple param: ” + p1 + “, ” + p2);
@FunctionalInterface
interface Drawable{
	public void draw();
}

@FunctionalInterface
interface Drawable2 {
	public void draw2(int dimension);
}

@FunctionalInterface
interface Drawable3 {
	public void draw3(int length, int width);
}

public class LambdaExpressionDemo {
	public static void main(String args[]) {
		int size = 10;
		
		//No parameter without return statement
		Drawable d1 = () -> {
			System.out.println("Drawable "+size);
		};
		
		//No parameter with return statement
		Drawable d2 = () -> {
			return size;
		};
		
		//Single parameter with return statement
		Drawable d3 = (dimension) -> {
			return dimension;
		};
		
		//Multiple parameter without return statement
		Drawable d4 = (a,b) -> (a+b);
		d1.draw();
		d2.draw();
		d3.draw2(5);
		d4.draw3(1,8);
		
		//Multiple parameter with return statement
		Drawable3 d5 = (int a, int b) -> {
			return (a+b);
		};
		
		//LambdaExpression to filter stream
		List<Product> list = new ArrayList<Product>();
		list.add(new Product(1, "Samsung A5", 17000f));
		Stream<Product> filtered_data = list.stream().filter(
			product -> product.price > 20000
		);
		
		//LambdaExpression on foreach loop
		filtered_data.forEach(
			product -> System.out.println(product.price)
		);
	}
}