# Lambda expression

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.

Lambda expression is used to implement a functional interface abstract method.

Functional Interfaces and lambda expression are introduced in Java 8.

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:

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

@FunctionalInterface
public interface MyFunctionalInterface {
    void sendEmail(String messageToSend);
}

The next step is to use the lambda expression:

The implementation of the functional interface class
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");
	}

}

When we run the application we can see in the console log:

--------------------------------------------
Text of my email.
Hello !
--------------------------------------------
End of the execution

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.