Tag Archives: lambda expression example

Java 8: Lambda Expression


Java 8 introduced lambda expression to move toward functional programming. A lambda expression is an anonymous function that doesn’t have a name and doesn’t belong to any class.

Where to use the Lambda Expression

A lambda expression can only be used where the type they are matched against is a single abstract method(SAM) interface or functional interface.

To use a lambda expression, you can either create your own functional interface or use the predefined functional interface provided by Java.

Example of a pre-defined interface: Runnable, callable, ActionListener, etc.

Pre Java 8: Use anonymous inner classes.
Post-Java 8: Now use lambda expression instead of anonymous inner classes.

Points to remember

  • Lambda expression is also known as a closure that allows us to treat functionality as a method arguments (passing functions around) or treat code as data.
  • Lambda expression concept was first introduced in the LISP programming language.
  • Lambda expression is used to provide an implementation of a functional interface or Single Method Interface.
  • Lambda expression treated as a function so the compiler does not create .class file.
  • Lambda expression doesn’t need to define a method again for implementation.
  • Lambda expression benefit is less coding.

Java Lambda expression Syntax

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


 (parameter_list) -> {function_body}

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

Note:

  • Optional type declaration: No need to declare the data type of a parameter. The compiler can inference the data type from the value of the parameter.
  • The optional parenthesis around parameter: No needs to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces: For a single line of the statement, No need to use curly braces in the expression body.
  • Optional return keyword: The compiler automatically returns the value if the body has a single expression statement to return the value. Curly braces are required to indicate that expression statement returns a value.

Here is some Lamda expression example according to a number of arguments.

No Argument Syntax


()->{
//write some statemnet here
}

One Argument Syntax


(arg1)->{
//write some statemnet here
}

Two Argument Syntax


(arg1,arg2)->{
//write some statemnet here
}

Method vs Lambda Expression in Java

A function (or method) in Java has four main parts:
1. Name
2. Parameter list
3. Body
4. return type.

A lambda expression has these main parts:
Lambda expression only has a parameter list and body.
1. No name – Lambda expression is an anonymous function that doesn’t have a name.
2. Parameter list
3. Body – This is the main part of the function where implementation is written.
4. No return type – Don’t need to write a return statement explicitly. The compiler is able to infer the return type by checking the code.

Example 1: Lambda Expression with a predefined functional interface

In this thread, execution example consider both ways legacy and lambda expression to implement the run method and start threads.

public class PredefinedFunctionalInterfaceExample {
public static void main(String[] args) {

// Implementing Runnable using anonymous class (legacy way)
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("Thread name : " + Thread.currentThread().getName());
}
};
Thread thread1 = new Thread(runnable1);

// Implementing Runnable using Lambda expression because Runnable having
// only one abstarct method run()
Runnable runnable2 = () -> {
System.out.println("Thread name : " + Thread.currentThread().getName());
};
Thread thread2 = new Thread(runnable2);

// Start Threads
thread1.start();
thread2.start();
}
}

Example 2: lambda Expression with your own functional interface

In this example, define the functional interface “YourFunctionalInterface” definition by the lambda expression for arguments (a,b). When we call the functional interface method with the argument (120,100) then it will make reference to the given definition of FunctionalInterface and return the result as 220.

@FunctionalInterface
interface YourFunctionalInterface
{
 public int addValues(int a, int b);
}

public class CalculateClass {

   public static void main(String args[]) {
        // lambda expression
    YourFunctionalInterface sum = (a, b) -> a + b;
        System.out.println("Result: "+sum.addValues(120, 100));
    }
}

Output


Result: 220

Example 3: Lambda Expression with no arguments

@FunctionalInterface
interface MyFunctionalInterface {
//abstarct method with no argument
public String sayWelcome();
}
public class LambdaExpressionExample {
public static void main(String args[]) {
//No argument lambda expression
MyFunctionalInterface msg = () -> {
return "Welcome to Facing Issues on IT !!";
};
System.out.println(msg.sayWelcome());
}
}

Output


Welcome to Facing Issues on IT !!

Example 4: Lambda Expression for Collection Iteration

import java.util.*;
public class LambdaExpressionLoopExample{
public static void main(String[] args) {
List list=new ArrayList();
list.add("Saurabh");
list.add("Gaurav");
list.add("Bharti");
list.add("Herry");
list.add("Henry");
list.forEach(
// lambda expression for list iteration
(names)->System.out.println(names)
);
}
}

Output


Saurabh
Gaurav
Bharti
Herry
Henry

Note:

  1. As you can see from these examples lambda expression used less code.
  2. Lambda expression is backward compatible so we can enhance our existing API when migrating to Java 8.

References

Advertisements