This article is about the Java 8 Feature – The Lambda Expression.

What is a Lambda Expression?

A lambda expression is a way to write anonymous functions in Java. It is a concise way to write a function without defining a separate function name, return type, or modifier.

This means a Lambda Expression is an anonymous function that:

    1. Has no modifier.

    2. Has no return type. 

    3. Has no name.

We can represent a regular function with a lambda expression. You need to take a few steps to make any function a lambda expression as follows:

    1. Remove modifier

    2. Remove return type.

    3. Remove method name.

    4. Place an arrow sign.

A traditional function is represented as :

Modifier Return_Type Function_Name(){

    Function body;

}

Conversion 1:

Example: Public void HelloJava8()

{

    System.out.println(“Hello Java”);

}

Let’s write the HelloJava8 function in a lambda expression representation. To do that, read the steps to be followed for the same mentioned above. Remove the modifier, return type, and function/method name. The above function in Lambda expression will look like:

() -> { System.out.println(“Hello Java”); }

Conversion 2:

What if the function has parameters?

Let’s take an example.

Public void HelloJava8(int a, int b)

{

    System.out.println(a+b);

}

The lambda expression for the above method would be 

(int a, int b) -> { System.out.println(a+b); }

Conversion 3:

Public int HelloJava8(String str)

{

    return str.length();

}

The lambda expression for the above method would be 

(String str) -> {return str.length();}

Now, we are familiar with how to write a lambda expression. Let’s talk about how these expressions can be further made concise.

1. If the expression has just one statement, we can remove the curly brackets.

Example: (String str) -> return str.length();

2. Use type inference, the compiler will guess the variable types.

Example: From conversion 2,

(a, b) -> { System.out.println(a+b); }

3. No need for return Keyword.

Example: From conversion 3,

(str) ->  str.length();

4. If only a single parameter, remove small brackets.

Example: From conversion 3,

str ->  str.length();

Conclusion:

The lambda expression is used to:

1. Enable functional programming.

2. Make code readable, concise, and maintainable.

3. Ensure parallel processing.

4. Ensure less jar file size.

5. Eliminate shadow variable.

Leave a Reply

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




Enter Captcha Here :