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.
 
lambda expression
 

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

Java 8 new features

Top 10 Tricky Java Puzzles

Top 10 Recursion Coding Interview Questions

Top Java Tutorial Articles : March 2016

 
 

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

2 Responses

  1. Isidro says:

    I want to thank you your splendid tutorial.
    I’m understanding the new Java 8 features so well.

  1. July 14, 2017

    […] Block Lambda Expression […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: