#
Lambda expression
A Functional Interface is an interface which contains exactly one abstract method
.
It can have any number of default, static methods but can contain only one abstract method.
Lambda expression
is used to implement a functional interface abstract method.
Functional Interfaces and lambda expression are introduced in Java 8.
Info
A "lambda expression" is a short block of code with parameters and without name.
For testing a Lambda expression, we need to create a Functional Interface first or to use a predefined one.
In my example, I start from a simple Spring Boot application created using Spring initializr.
The first step is to create the functional interface:
package com.exampe.java.interfaces;
@FunctionalInterface
public interface MyFunctionalInterface {
void sendEmail(String messageToSend);
}
Info
@FunctionalInterface
is used in Spring for testing if we have only one abstract method in the interface and for documentation.
The next step is to use the lambda expression:
package com.exampe.java;
import com.exampe.java.interfaces.MyFunctionalInterface;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("--------------------------------------------");
MyFunctionalInterface mfi = (String x) -> {
System.out.println(x);
System.out.println("Hello !");
};
mfi.sendEmail("Text of my email.");
System.out.println("--------------------------------------------");
System.out.println("End of the execution");
}
}
Info
In my example, (String x) -> { System.out.println(x); System.out.println("Hello !"); }
is the lambda expression.
This implements the sendEmail
method. The abstract method signature must match the lambda signature, which is named
functional descriptor.
When we run the application we can see in the console log:
--------------------------------------------
Text of my email.
Hello !
--------------------------------------------
End of the execution
Info
- A Lambda expression could modify a Class/Object instance variable, but not a variable which is defined in the method where lambda expression is used.
There are a couple of predefined functional interfaces:
Predicate<T>
orBiPredicates<T,U>
: used for filters, we need to define test(T) or test(T, U) method. This method returns a boolean value.Consumer<T>
orBiConsumer<T,U>
: we need to define accept(T) or accept(T, U) method. This method returns no value.Supplier<T>
: we need to return theobject . The get() method will be used to obtain the object returned by the supplier.Function<T, R>
orBiFunction<T,U,R>
: we need to define apply(T) or apply(T, U) method. This method returns an R object.UnaryOperator<T>
orBinaryOperator<T,T>
: we need to return a T object.
Info
T, U, R are generic types of objects.