Java 8 Lambda Expression

Java 8 Lambda Expression thumbnail
9K
By Dhiraj 12 May, 2017

This article is all about java 8 lambda expressions. Here we will discuss about what is lambda expression, why is it required although we have object oriented programming, different ways of using lambda. We will also write a sample hello world java program using lambda expression and functional interface and many more. So lets get started.

What is Lambda Expression

Lambda is a programming paradigam that enables functional programming. It provides an inline implementation of a functional interface which does not belong to a class and it is treated as a value in functional programming and this introduced the concept of Functional Interface in java 8.

As we know in the object oriented programming model, a method is associated to a class but in case of functional programming a method can be created without belonging to any class and can be reused anywhere without creating any instance of an object and can be executed on demand. Hence, it is also said that lamda expressions are lazy loading.

Now, let us understand what is a functional interface and then we can relate the lambda expression with functional interface to make more sense of it.

Functional interface is an interface that performs only a single operation as we can only declare single abstract method in a functional interface but it can have multiple default methods.

@FunctionalInterface
public interface OperateInterface {

    int operate(int x, int y);

    default void addMessage(){
        System.out.println("Perform addition");
    }

    default void subtractMessage(){
        System.out.println("Perform subtraction");
    }
}

In the traditional approach, we can't invoke an abstract method of an interface without a class implementing the interface and provide an implementation of the method meaning without associating it with an object.

But as we discussed above that a Lambda expression provides an implementation of a functional interface without being associated with a class. Hence, let us see how this method can be invoked using a lambda expression.

public static void main(String[] args){
        OperateInterface multiplication = (x, y) -> x * y;
        int mult = multiplication.operate(6, 7);
        System.out.println(mult);
        OperateInterface addition = (x, y) -> x + y;
        int add = addition.operate(6, 7);
        System.out.println(add);
    }

Here, we provided the implementation for multiplication and addition of two numbers.

Now, we can conclude that a lambda expression lets you provide an implementation of an abstract method of a functional interface directly inline and treat the whole expression as an instance of a functional interface.

By this time, you might have identified multiple functional interface which are already there before Java 8 such as Runnable, Callable and Comparable interface. Runnable interface has only one method as run()

Below is a sample lambda expression implementation of run() method. We will discuss more on such functional interface in our next article.

new Thread(() -> System.out.println("run() method implementation with a lambda expression.")).start();

Why Lambda Expression

Lambda enables functional programming and its not like functional programming does something which is not possible through object oriented programming. The same implementations of object oriented programming can be achieved in functional progamming in a concise manner with more clearer and flexible codes. We can avoid many boiler plates code with functional programming. It also enables parallel processing.

 Other Interesting Posts
Java 8 Stream Operations
Java 8 Datetime Conversions
Java 8 Parallel Streams
Java 9 Modularity Features

Lambda Expression Syntax

Following is the syntax of a Lambda expression.

(parameters) -> {statements;}

The parameters can be either empty or can have multiples.Following is the example.

Zero Parameter
() -> System.out.println("Zero parameter");

One Parameter
(p) -> System.out.println("Single parameter" + p);

Multiple Parameters
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);

The statements are the body of a function. If you have a single statement you can write a lambda expression as:

() -> System.out.println("Single line statements.");

Similarly, if you have multiple lines of statements, your lambda expression looks something like

(p1, p2) -> {
    System.out.println("parameter1" + p1);
    System.out.println("parameter2 " + p2);
  }
  

Hello World Example with Lambda Expression

Following is a method that prints Hello World in object oriented programming.

public void hello(){
        System.out.println("Hello World");
    }
	

Above code using lambda expressions will be something like

() -> System.out.println("Hello World");

Returning Value From Lambda Expression

Following is a lambda expression syntax that accepts two integers and returns sum of it.

(int a, int b) -> return a+b;

Note:If the type of the parameters can be decided by the compiler, then we do not require to declare type.

(a,b) -> return a+b;

If the body has just one expression, the return keyword can also be omitted.

(int a, int b) -> a + b

Executing Lambda Expression

Let us create a functional interface first. Functional interface is an interface that has only one abstract method.

package com.devglan;

public interface FunctionalInterface {
	
	 void hello();

}

Now we can execute it as follow. Lambda expression is assigned to a variable first, and then the lambda expression is invoked by invoking the interface method it implements.

package com.devglan;

public class FunctionalInterfaceExample {

    public static void main(String[] args) {
       
        FunctionalInterface lambda = () -> {System.out.println("Hello World");};
        
        lambda.hello();
    }
    
}

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Java 8