#
Functional Interfaces
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.
Functional Interfaces introduced in Java 8 allow us to use a lambda expression.
Info
A "lambda expression" is a short block of code with parameters and without name.
For testing a Functional Interface in Spring Boot, after creating a simple application, you can add the following classes:
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.
package com.exampe.java.implementation;
import com.exampe.java.interfaces.MyFunctionalInterface;
public class MyFunctionalInterfaceImpl implements MyFunctionalInterface {
public void sendEmail(String messageToSend) {
System.out.println("I send a message with the following message: \n \""+messageToSend+"\"");
}
}
Also, we need to modify the main application class:
package com.exampe.java;
import com.exampe.java.implementation.MyFunctionalInterfaceImpl;
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);
MyFunctionalInterfaceImpl sendMessage = new MyFunctionalInterfaceImpl();
System.out.println("--------------------------------------------");
sendMessage.sendEmail("He is available today. Please call him.");
System.out.println("--------------------------------------------");
System.out.println("End of the execution");
}
}
When we run the application we can see in the console log:
--------------------------------------------
I send a message with the following message:
"He is available today. Please call him."
--------------------------------------------
End of the execution
Process finished with exit code 0
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.
