DEV Community

Cover image for Lambda Expressions in Java
Nitish-op
Nitish-op

Posted on • Updated on

Lambda Expressions in Java

Introduction

Lambda expressions are similar to methods, but they are anonymous methods (methods without names) used to implement a method defined by a functional interface and they can be implemented right in the body of a method. A lambda expression is a short block of code which takes in parameters and returns a value so they implement the only abstract function and therefore implement functional interfaces.

Syntax

(parameters) -> { code block }

The left side specifies the parameters required by the expression, which could also be empty if no parameters are required.

The right side is the lambda body which specifies the actions of the lambda expression. The body of a lambda expression can contain zero, one or more statements.

When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.

When there are more than one statements, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.

Using Lambda Expressions

1.Example: No Parameter

interface Trigger{

public String display();

}

public class LambdaExpressionExample3{

public static void main(String[] args) {

Trigger s=()->{ return "Lambda function is used";};

System.out.println(s.display());

}

}

2.Example: Single Parameter(can also be with multiple parameter)

interface NumericTest {
boolean computeTest(int n);
}

public static void main(String args[]) {
NumericTest Even = (n) -> (n % 2) == 0;
NumericTest Negative = (n) -> (n < 0);
System.out.println(Even.computeTest(10));
System.out.println(Negative.computeTest(-9));
}

3.Lambda expressions as arguments

interface MyString {
String myStringFunction(String str);
}

public static String reverseofStr(MyString reverse, String str){
return reverse.myStringFunction(str);
}

public static void main (String args[]) {
// lambda to reverse string
MyString reverse = (str) -> {
String result = "";
for(int i = str.length()-1; i >= 0; i--)
result += str.charAt(i);

return result;
};
System.out.println(reverseofStr(reverse, "Lambda example"));
}

lambda expressions are added in Java 8 to provide functionalities such as
Enable to treat functionality as a method argument, or code as data.

A function that can be created without belonging to any class.

A lambda expression can be passed around as if it was an object and executed on demand.

so it saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation.

Top comments (0)