Java Lambda Expression

Lambda expression is a way to represent the method interface using an expression. The expression is treated as a method. It was introduced in Java 8 to provide an interface helping in iterating, filtering, and extracting data from the collection. It has great significance in the Collections library. The lambda expression has its resemblance to the method but it is not required to define again for the implementation like methods. Instead, we only write the implementation.

Why?

  • Less Coding is required
  • Lambda Expression is used to provide the implementation of a Functional interface( An interface which has only one abstract method ). Java provides an annotation @FunctionalInterface  to declare an interface as a functional interface.

Syntax

(argument-list) -> {body}  

Java lambda expression consists of two components.

  • Argument-list: It can be empty or non-empty as well. The arguments are comma-separated and enclosed by ().
  • Body: It contains the implementation of a lambda expression. It is enclosed by {}.

We use an arrow(->) to link the argument-list with the body.

Example:

//No Parameter Syntax
() -> { 
//Body 
}  

//Two  Parameter Syntax
(param1, param2) -> { 
//Body
}  

Let us take an example to show the difference lambda expression’s presence makes in code.

Without  Lambda Expression

interface MyInterface{      
public void myMethod();  
}  

public class LambdaTest {  
    public static void main(String[] args) {  
        MyInterface obj=new MyInterface (){  
            public void myMethod (){System.out.println("I am implementation of myMethod.");}  //Using anonymous class
        };  
        obj.myMethod();  
    }  
}

 Output:

I am implementation of myMethod.

With Lambda Expression

@FunctionalInterface
interface MyInterface{
public void myMethod();
}

public class LambdaTest {
public static void main(String[] args) {
MyInterface obj=()->{System.out.println("I am implementation of myMethod using Lambda Interface.");};
obj.myMethod();
}
}

Output:

I am implementation of myMethod using Lambda Interface.

We can see that the implementation can be done seamlessly, unlike the use of the anonymous class process discussed.

There can be multiple parameters in the functional interface, and the implementation will be also done accordingly.

@FunctionalInterface
interface MyInterface{
public void myMethod(int a,int b);
}

public class LambdaTest {
public static void main(String[] args) {
MyInterface obj=(a,b)->{System.out.println("The two parameters we took are "+a+" are "+b);};
obj.myMethod(4,5);
}
}

Output:

The two parameters we took are 4 are 5

Till now, we have seen lambda expressions without any return. On the basis of the return type of the method inside the functional interface, we can also return from the lambda expression. Also, note that since it is a block, it can have multiple statements.

@FunctionalInterface
interface MyInterface{
public int myMethod(int a,int b);
}

public class LambdaTest {
public static void main(String[] args) {
MyInterface obj=(a,b)->{
System.out.println("The two parameters we took are "+a+" are "+b);
return(a+b);
};
System.out.println("The sum is "+obj.myMethod(4,5));
}
}

Output:

The two parameters we took are 4 are 5
The sum is 9

Let us now see the combination of Generics and Lambda Expression in the below code. We see a generic Interface MyInterface with a single type parameter T. The reference obj is of type Integer and has its own individual implementation without any intervention of other instances. Similarly, obj2 is of type String and has its completely different implementation which is independent in nature.

@FunctionalInterface
interface MyInterface<T>{
public void myMethod(T a);
}

public class LambdaTest {
public static void main(String[] args) {
MyInterface<Integer> obj=(a)->{
    System.out.println("I will print multiplication table of "+a); 
    for(int i=1;i<=10;i++)
        System.out.println(a+" * "+i+" = "+(a*i));
    };
obj.myMethod(5);


MyInterface<String> obj2=(a)->{
    System.out.print("\n\nI will print the reverse of string "+a+"\nReverse: "); 
    for(int i=a.length()-1;i>=0;i--)
        System.out.print(a.charAt(i));
    };
obj2.myMethod("madhurav");
}
}

Output:

I will print multiplication table of 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50


I will print the reverse of string madhurav
Reverse: varuhdam

This was an overview of Lambda Expression. Hope this lecture module helps you clear the basics of Java and encourage you to start self-experimenting.