What is a functional interface in Java?



An interface with only one abstract method is known as Functional Interface. @FunctionalInterface annotation can be added so that we can mark an interface as a functional interface. The Java compiler automatically identifies the functional interface.

The lambda expressions are used primarily to define the inline implementation of a functional interface. It eliminates the need for an anonymous class and gives a simple and powerful functional programming capability to Java.

Few java default interfaces are functional interfaces listed below

  • java.lang.Runnable
  • java.util.concurrent.Callable
  • java.io.FileFilter
  • java.util.Comparator
  • java.beans.PropertyChangeListener

Syntax

@FunctionalInterface
interface interface-name {
 // only one abstract method
}

Example

@FunctionalInterface
interface MathOperation {
   int operation(int a, int b);
}
public class LambdaExpressionTest {
   public static void main(String args[]) {
      MathOperation addition = (a, b) -> a + b;  // lambda expression
      MathOperation multiplication = (int a, int b) -> { return a * b; };  // lambda expression
      System.out.println("The addition of two numbers are: " + addition.operation(5, 5));
      System.out.println("The multiplication of two numbers are: " + multiplication.operation(5, 5));
   }
}

Output

The addition of two numbers are: 10
The multiplication of two numbers are:: 25

Advertisements