Basic Tutorial for Lambda Expressions in Java 8

By | | Updated : 2020-12-25 | Viewed : 163 times

basic-tutorial-for-lambda-expressions-in-java8

The current tutorial describes the lambda expressions and their usage with detailed examples. So let's start the tutorial for learning the lambda expressions.

What are Lambda Expressions Java 8?

Lambda Expression has been introduced in Java 8 as an initial step to introduce the functional style of programming. Lambda Expression is a function/method body where a function/method body does not belong to any other Class. Lambda Expression lets us allow passing the method body.

Example of Lambda Expression
MathOperations operationsAdd = (a, b) -> a + b;
int resultAdd = operationsAdd.operation(20, 10);
System.out.println(resultAdd);

MathOperations operationsSub = (a, b) -> a - b;
int resultSub = operationsSub.operation(20, 10);
System.out.println(resultSub);

The above-given code is an example of Lambda expression. Here we are trying to call the method operation(); of functional interface MathOperations; The expression should match with the signature against the abstract method in the functional interface wherein the function signature is written. Here we are able to pass the two different types of expression one is a + b and another one is a - b. So both operations can be calculated with only one method of functional interface.

Why Lambda Expressions introduced in Java 8?

Functional Programming:

First of all, we should understand the Functional style of programming in Java 8. Functional Programming is implemented and constructed with expressions in a declarative manner, not like statements. These expressions make the readability of the code neat and clean. Moreover, These expressions shortly describe the logic.

It is highly required to understand the importance of Lambdas. Let\'s discuss the importance of Lambda Expression in Java. For that, we will write an example to understand the importance of Lambdas Expression.

Please consider the below-given example for the Vehicle.

Vehicle.java
public interface Vehicle {
    public String getVehicleBrand();
}

To implement this Vehicle interface it is required the implementation class as given below.

Audi.java
public class Audi implements Vehicle {
    public String getVehicleBrand() {
        return "Audi";
    }
}
MercedesBenz.java
public class MercedesBenz implements Vehicle {
    public String getVehicleBrand() {
        return "Mercedes Benz";
    }
}

As defined in the above all class, it is required to implement getVehicleBrand(); in different classes.

To avoid too many definitions of method and increase the readability of code, we can use the Lambda Expressions. For that use of the Lambda Expressions, it is required to make the interface as a Functional interface. let\'s have a look at what is the Functional Interface?

Vehicle.java
@FunctionalInterface
public interface Vehicle {
    public String getVehicleBrand();
}

Notice the above Functional Interface contains only one Single Method which should be abstract.

The above interface will be passed as an instance expression wherever it is required to execute. For example, if we want to execute the above single method interface in the Audi class then we can pass the instance of the functional interface as given below.

Audi.java
public class Audi {
    public void displayAudiFeatures() {
        Vehicle vehicle = () -> { return "Audi.";};
        String brand = vehicle.getVehicleBrand();
        System.out.println(brand);
    }
}
MercedesBenz.java
public class MercedesBenz {
    public void displayAudiFeatures() {
        Vehicle vehicle = () -> { return "MercedesBenz."; };
        String brand = vehicle.getVehicleBrand();
        System.out.println(brand);
    }
}

Notice the above-given example does have an implementation of getVehicleBrand() in the form of functional-style programming.

To achieve the functional style of programming we use the lambda expressions.

How does Lambda Expression work?

Java will follow these steps below to execute the suitable lambda expression against to abstract method of Functional Interface.

  • Java Functional interface should contain only one abstract method.

  • The parameter of the abstract method should match with lambda expression parameters.

  • The return type of lambda expression should be the same abstract method in Functional Interface.

What is the Syntax of Lambda Expressions?

The Generalized syntax of Lambda expression is

General Example of Lambda Expression
lambda parameter->(method body)

There are three types of variation are there.

Zero Parameterized

Zero Parameterized Lambda
() -> {}

Single Parameterized

Single Parameterized Lambda
(p) -> {return p;}

Multi Parameterized

Multi Parameterized Lambda
(p1,p2) -> {return p1+p2;}

Anonymous Inner Class vs Lambdas

If you have experience in the implementation of Listener in Java you might have known about the Anonymous Inner class.

For instance to understand what is Anonymous Inner class Please look into the below given example.

FunctionalInterface Example
public void static void main(String []args){
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Inside of Anonymous class");
                Employee employee 	= 	new Employee();
            }
        };
    }

So here we can create the body of any interface and can define the instance variables. This means it is an implemented class of that interface.

We can rewrite the above code with lambda expressions as

Lambda Expression Example
Runnable r2 = () -> {
    System.out.println("In side of Lambda Expression");
};

If you notice the above lambda expression it does not contain any instance variables. But we can write the lambda expression only for single-method interfaces.

Difference between Lambda and Anonymous Inner Class

  • When an interface contains more than one abstract method then it is not possible to use lambda.

  • In lambda expressions, this and super keywords represent the current class wherein Anonymous Inner Class these keywords represent that particular anonymous inner class.

  • In the case of anonymous inner class the new class file will be created whereas the new class file will not be created.

  • It requires to write the redundant class definition code in an anonymous inner class where it is not required in case of Lambda Expression and sufficient pass required parameter and body.

Lambda Expression and its Parameters

So far we did not implement Lambda Expressions with different types of parameters. So we will discuss the same here.

Zero Parameterized Lambda: Please consider the below given example. Here we are going to define the Vehicle interface;

Vehicle1.java
@FunctionalInterface
public interface Vehicle1 {
    public void displayVehicleName();
}

The implementation of the above abstract method using lambda is given below.

ZeroParameterizedLambda.java
public class ZeroParameterizedLambda {
    public static void main(String[] args) {
        Vehicle1 vehicle1 = () -> {
            System.out.println(" The Vehicle brand is Audi.");
        };
        vehicle1.displayVehicleName();
    }
}

Single Parameterized Lambda: Consider below given example for Single Parameterized Lambda Expression.

Vehicle2.java
@FunctionalInterface
public interface Vehicle2 {
    public void displayVehicleName(String brand);
}

The implementation of the above abstract method is as given below.

SingleParameterizedLambda.java
public class SingleParameterizedLambda {
    public static void main(String[] args) {
        Vehicle2 vehicle2 = (brand) -> {
            System.out.println(" The Vehicle brand is " + brand + ".");
        };
        vehicle2.displayVehicleName("Audi");
    }
}

Multi Parameterized Lambda Expression: Sometimes it is required to pass the multiple params to the Lambda Expression.

Vehicle3.java
@FunctionalInterface
public interface Vehicle3 {
    public void displayVehicleName(String brand, String FuelType);
}

The lambda implementation is as given below. Please see the code snippet below.

MultiParameterizedLambda.java
public class MultiParameterizedLambda {
    public static void main(String[] args) {
        Vehicle3 vehicle3 = (brand, fuelType) -> {
            System.out.println(" The Vehicle brand is " + brand +
                    " with Fuel type" 	+ fuelType + ".");
        };
        vehicle3.displayVehicleName("Audi", "Diesel ");
    }
}

Note: If the type of the parameter is not matched then the compiler will alert as a compile error.

Leave A Reply