# Functional Interfaces

In 
Published 2022-12-03

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.

For testing a Functional Interface in Spring Boot, after creating a simple application, you can add the following classes:

The functional interface class
package com.exampe.java.interfaces;

@FunctionalInterface
public interface MyFunctionalInterface {
    void sendEmail(String messageToSend);
}
The implementation of the functional interface class
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> or BiPredicates<T,U>: used for filters, we need to define test(T) or test(T, U) method. This method returns a boolean value.

  • Consumer<T> or BiConsumer<T,U>: we need to define accept(T) or accept(T, U) method. This method returns no value.

  • Supplier<T> : we need to return the object. The get() method will be used to obtain the object returned by the supplier.

  • Function<T, R> or BiFunction<T,U,R>: we need to define apply(T) or apply(T, U) method. This method returns an R object.

  • UnaryOperator<T> or BinaryOperator<T,T>: we need to return a T object.