Java 8 Block Lambda Expressions
In this article, we will understand the difference between Expression lambdas and Block lambdas. We will also see how to create Block lambda expressions.
Prerequisite
This article assumes understanding of basics of Lambda expression in Java.
You can refer this article for the same :
Java 8 Lambda Expressions Introduction
Expression Lambdas vs Block Lambdas
The lambda expressions that have a single expression in the body are know an Expression lambdas.
Java also supports second type of lambda expression where the lambda expression body contains a block of code rather than just a single statement. This type of lambda expression are called Block lambdas.
In the block lambda expression, we must explicitly use a return statement to return a value.
Creating Block Lambda Expressions
To create a block lambda expression, we can enclose the body within braces as shown below :
MathFunctions mathFunc = (n) -> {
//block of code
};
In the below program, we use a block lambda expression to calculate and return the factorial of a number.
package com.topjavatutorial.java8examples; public interface MathFunctions { int factorial(int n); }
The MathFunctions functional interface declares the factorial method. This method takes an integer argument and returns an integer value.
package com.topjavatutorial.java8examples; public class LambdaBlockDemo { public static void main(String[] args) { MathFunctions mathFunc = (n) -> { int fact = 1; for(int i =1;i <= n;i++){ fact = i * fact; } return fact; }; System.out.println("Factorial(5) = " + mathFunc.factorial(5)); } }
Output
Factorial(5) = 120
In the above example, we created a block lambda expression and declared a variable fact in it to store factorial value.
Then we added a for loop, that evaluates factorial of a number and returns it.
The return statement just returns the control from the lambda; it does not cause an enclosing method to return.
You may also like reading
© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post
I want to thank you your splendid tutorial.
I’m understanding the new Java 8 features so well.