A brief Introduction of Lambda Expression in Java: How to use Lambda Expression

Reading Time: 4 minutes

Lambda Expression in Java

java logo with lambda expression

As Java 8 was released in 2014, which brought with it a lot of new features and changes. Among these changes were features that allowed Java developers to write in the functional programming style. To support functional programming style, a language needs to support functions as first class citizen. One of the biggest changes was the addition of lambda expressions.

Because the organisations slowly move to the Java 8 and Java 11 platforms, more and more developers are finding the opportunity to use lambda expressions. It simplifies the development a lot.

What is Lambda Expression ?

Generally, A lambda expression is a function in java which can be created without belonging to any class. A Lambda expression (function) is an anonymous function, for example: a function with no name and any identifier.

Lambda Expressions are the foundation of functional programming in Java, In other words, Lambda expressions are the java’s first step in functional programming. Lambda expression is a very new and exciting feature of Java 8.

Why are they called ‘lambda functions’ ?

In mathematics, a lambda function is one in which a single set of assigned variables are mapped to a calculation.

For example.

(x) = x2
(x, y) = x + y

For the first equation, if x is 4, the function would evaluate to 16. If x and y are both 3 for the second function, the result is 6.

Lambda Expression Syntax

To specify input parameters (if there are any) on the left side of the lambda operator ->, and place the expression or block of statements on the right side of lambda operator.

For example, a lambda expression (a, b) -> a + b specifies that lambda expression takes two arguments a and b and returns the sum of these.

(parameter_list) -> {function_body}

(a,b) -> a+b // it returns the sum of two numbers

They are callable anywhere in the program and can be passed around. In simple term, lambda expressions allow functions to behave like just another piece of data.

These are the important points of a lambda expression.

  • If there is no multiple parameters then we don’t need to declare a single parameter in parenthesis.
  • If the body contains single statement then we don’t need to use curly braces in expression body because curly braces are optional.
  • The compiler automatically returns the value if the body has a single expression to return the value.
  • For no parameter Syntax
() -> System.out.println("No parameter lambda");
  • With one parameter Syntax
(str) -> System.out.print(str); // single argumment, lambda expression
  • With multiple parameters Syntax
(x, y) -> System.out.println("Multiple parameters: " + x +", "+y);

Why we use lambda expression in Java?

  • Because it enables functional programming in Java .
  • To write maintainable , readable and concise code in Java.
  • Lambda expressions can be stored in variables if the type of a variable is an interface which has only one method.
  • To use API very easily and effectively we use lambda expression in Java.
  • Java lambda expressions are commonly used to implement simple event listeners or callbacks. In other words, It is used in functional programming with the Java Streams API.
  • Because it reduces the lines of code.

Functional Interface why it is important to write lambda function.

Before Java 8, we had to create an inner anonymous class to use these interfaces.

For example: without lambda expression.

// functional interface before java 8
  
class Test 
{ 
    public static void main(String args[]) 
    { 
        // create anonymous inner class object 
        new Thread(new Runnable() 
        { 
            @Override
            public void run() // anonymous class
            { 
                System.out.println("Thread created"); 
            } 
        }).start(); 
    } 
} 

By using Lambda expression: Instead of creating anonymous inner class, we can create a lambda expression by using functional interface.

Functional Interface

Lambda expressions can only implement functional interfaces, interface that has only one abstract method. Similarly, lambda expression essentially provides the body for the abstract method within the functional interface.

If there are more than one abstract method in the interface , the compiler would not know which method should use the lambda expression as its body.

To use lambda expression, we need to create our own functional interface.On the other hand we can use the pre-defined functional interface provided by Java.util package.

 For example: Runnable, Callable, ActionListener etc.

These kinds of interfaces are called Functional interfaces and they are annotated with @FunctionInterface annotation. The best practice to add the optional @FunctionalInterface annotation to the top of any functional interface.

Program to demonstrate the working of lambda expression in Java by creating functional interface.

// creating functional interface
@FunctionalInterface
interface MyFunctionalInterface {
    
    void operation(int a, int b);
}

Creating class

//creating class
public class LambdaTest1 {
  public static void main(String[] args) {
    // Lambda Expreassion 1
    MyFunctionalInterface f = (int a, int b) -> {
     return a + b;
    };
    System.out.println(f.operation(4, 5));// 9

    // Lambda Expreassion 2
    MyFunctionalInterface f2 = (a, b) -> a * b;
    System.out.println(f2.operation(2, 5)); // 10


 // Lambda Expreassion 3
    MyFunctionalInterface f3 = (a, b) -> a / b;
    System.out.println(f2.operation(20, 5)); // 4
  }
}

With Single parameter and single statement

// creating functional interface
@FunctionalInterface
interface StringOpr {
    public int getLength(String str);
}
//creating class
public class Main {
  public static void main(String[] args) {
    // Lambda Expreassion 1
    StringOpr length= (str-> str.length();
    System.out.println("String length: "+length.getLength("hello"));
  }
}

Using pre-defined functional interface to create a thread by using Lambda

package learn.java.lambda;

public class ThreadDemo {
    public static void main(String[] args) {
        // first thread
        // Here we are using Runnable interface 
        Runnable thread1 =()->{
            // body of thread
            for (int i=0; i<5; i++)
            {
                try {
                    System.out.println("Thread is running");
                    Thread.sleep(1000);
                }catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        };
        Thread t =new Thread(thread1);
        t.start();
    }
}

Passing Lambdas as Objects

We can pass lambda lambdas to other functions as parameters. For example we are creating a greeting program.

package learn.java.lambda;

// creating functional interface
@FunctionalInterface
public interface Greeting {
    String greet(String msg);
}
package learn.java.lambda;

public class Wisher {
    public static void wish(Greeting greeting) {
       System.out.println(greeting.greet("Morning")); //Output: Good Morning Buddy

       System.out.println(greeting.greet("Evening")); //Output: Good Evening Buddy
    }
    // Passing a lambda expression to the wish method
    public static void main(String args[]) {
        wish((msg) -> "Good " +msg+ " Buddy");
    }
}


Conclusion

In this blog, we have learned about lambda expression. Lambda expression is a powerful tool to have, it reduces the lines of code and provide the way to enable functional programming in Java 8.

Java Lambda Expressions are useful in real-time software development.

Written by 

Aasif Ali is a Software Consultant at Knoldus Inc. He has done Post Graduation from Quantum University Roorkee. He has the knowledge of various programming languages. He is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is a quick learner, problem solver and always enjoy to help others. His hobbies are watching Sci-fi movies , Playing badminton and listening to songs.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading