Skip to main content

Lambda Expression

What is Lambda Expression?

In java 8, a powerful concept is added named Lambda Expression. Lambda expression is an anonymous function (a nameless function that does not have a modifier, return type, and even the type of its arguments). 
Lambda expression is that you can pass to a method whose argument type is functional interface i.e. an interface that is either annotated by @FunctionalInterface annotation e.g. interfaces from java.util.function package, or an interface with a single abstract method e.g. Comparable, Comparator, Runnable, Callable, ActionListener, etc. 
Lambda expression allows passing customized code to the java method that was not possible before java 8. Although before Java 8 the only option was to wrap your code as an object and pass it using anonymous inner class to the method. Lambda expression defines parameters and code that executed using those parameters. Let's take the simplest example of the lambda expression
(String input) -> System.out.print(input);
The orange part is the left-hand side(parameters side) and the red part is the right-hand side (implementation side of SAM) of Lambda expression. The symbol -> is a lambda operator.

How to write a Lambda Expression

The first thing you should remember while writing lambda is that you can only write lambda for the interfaces present inside package java.util.function or for SAM(Single Abstract method) interfaces e. g. Comparable, Comparator, Runnable, etc. The way of converting a SAM or a method of a predefined or user-defined functional interface into a lambda expression is to remove name, modifier, return type, and put the symbol -> after the method arguments and then provide the implementation for your lambda expression between curly braces. For example 

@FunctionalInterface
public interface FnctnalInterface {

public void abstractMethod();
@Override
public String toString();
}
Now let's write our first Lambda expression for the above mentioned functional interface.

() -> System.out.print("One Liner Lambda Expression"); 

The above lambda expression is a one-liner lambda expression. Curly braces and a return statement is not required if the lambda expression is a one-liner.

Java compiler has the ability to infer the method name, modifier, return type, and argument type from the functional interface method. That's why the functional interface contains only one abstract method so that java compiler easily infer the details. This is called type inference.

Inside lambda expression, you can't declare instance variable. The variables that declare inside the lambda expression have their scope up to the curly braces of the lambda expression and these variables are called local variables. One thing you should remember that the only applicable modifier inside the lambda expression is final for variables.
If you are using a local variable inside the lambda expression then that variable should be final or effectively final. For example

If you will run the above code in java 8 environment, it will run perfectly and print the output on the console. But now in java 8 if you will try to reinitialize the local variable that is currently used inside the lambda expression then compiler popup an error "Local variable effectiveFinal defined in an enclosing scope must be final or effectively final". You can try this by yourself in the above example by uncommenting the line number 14. This concept is called an effective final.
Now let's wrap this post with the last example. In this example, we will iterate over the list of string objects.

Thank you so much for reading this post. If you will find this post helpful then please share this post with your friends and colleagues. Please comment below if there is any query or feedback. I will try to respond back.

Comments

Popular posts from this blog

How to add an existing project to a GitHub Repository

  Add Existing project to a GitHub Repository Step 1: Login into your GitHub account and create a new repository. Step 2: Go to your project folder on your machine and open git bash. After that runs the command “ git init ”. This command initialized the empty git repository on your local machine. Step 3: Create a file “. gitignore ” using the command “ echo > .gitignore ”. Add the file extension or file name inside this file, those you don’t want to commit to your repository. Git will ignore all those files that will be present inside this file. Step 4: Add all the files to the staging area using the command “git add .” This command adds all the files to the staging area and all these files are now ready for the commit. And with the help of the command “git status” , you can check that all the files are inside the staging area. Also, you can see the file extension or the file name mentioned inside the “.gitignore”  are ignored by git. Step 5: Commit the files that are pre...

How to install IntelliJ IDEA on Windows?

System Requirements and steps to install IntelliJ IDEA on Windows System Requirements:  Step 1: Download IntelliJ IDEA. Click here. Step 2: Run the downloaded exe file and click on next. Step 3: Check the checkboxes mentioned in the below image and click on next and then hit the install button. Step 4: Final step is to reboot your system before start using IntelliJ IDEA. Thank you, guys. Please do comment below if there is any query or feedback.