Java 8 introduced the concept of functional interfaces, interfaces that contains exactly one abstract method. These interfaces are used extensively in lambda expressions, streams and in method references.
To make any interface as Functional Interface then we have to use the following annotation just above the interface @FunctionalInterface. The @FunctionalInterface annotation is used to indicate that an interface is intended to be a functional interface. This annotation is optional but provides compiler-level checks.
import java.util.*;
interface MyFunctionalInterface {
void myMethod();
}
public class MyClass {
public static void main(String[] args) {
MyFunctionalInterface fi = () -> System.out.println("my-method executed");
fi.myMethod();
}
}
my-method executed
xxxxxxxxxx
import java.util.*;
interface Calculator {
int operate(int a, int b);
}
public class Main {
public static void main(String[] args) {
// Using a lambda expression
Calculator addition = (a, b) -> a + b;
Calculator subtraction = (a, b) -> a - b;
System.out.println("Addition: " + addition.operate(5, 3));
System.out.println("Subtraction: " + subtraction.operate(5, 3));
}
}
Addition: 8
Subtraction: 2