November 28, 2018

What is lambdas in Java – Understanding Lamdas in Java

Lambdas were introduced in Java 8. For me they are first step towards functional programming in java.

Lambdas are a little like anonymous class. They are similar in the way they are defined and passed around as a parameter in functions. But, lambdas are not exactly an anonymous class. After compilation, an anonymous class has it’s own .class  file. But, lambdas are part of the same .class file in which it is defined.

Example 1 : A Lambda which takes nothing as a parameter and returns nothing as the return value.

Let us implement Runnable  interface using anonymous class. I will provide an empty body for the run method.

Runnable runFromAnoymousClass = new Runnable() {
@Override
public void run() {}
}

Now, i will use a lambda to provide the same implementation.

Runnable runFromLambda = () -> {}

We have provided an implementation of run method, by using lambda. This lambda takes no parameters and has empty body.

Example 2 : A Lambda Which takes nothing as parameter but returns a value.

Let us implement a Callable interface, using anonymous class.

Callable<String> returnMyName = new Callable<>(){
    @Override
    public String call () {
        return "Refactored Codes.";
    }
}

Now, we will use a lambda to provide the same implementation for Callable.

Callable<String> implementedByLambda = () -> "Refactored Codes."

Both the implementations will give the same output.

Example 3 :  A lambda which takes one parameter and returns a result.

For this example, we will use java.util.function.Function<T, R> , this interface has one abstract method apply . We will provide it’s implementation using a lambda.
This lambda will take a string, and it will return length of that string, as the output.

Function<String, Integer> lengthOfThisString = (word) -> word.length();
int length = lengthOfThisString.apply("Anurag Anand")
System.out.println("Length :- " + length);

it’s Output :- 

Length :- 12

 

Similarly, we can provide implementations for interfaces, which can take multiple inputs and provide a result.