Functional interface in Java

The interface which has only one abstract method its called functional interface. Functional interface can have multiple static and final method. And also can have the default method. If you annotate the interface with @FunctionalInterface java not allow the developer to add more than one abstract method. If the developer added more than one abstract method in the functional interface java throw the compile time exception.

Steps for creating functional interface

  • Create new interface
  • Annotate with @FunctionalInterface (Optional)
  • Create at least one abstract method

Here is the example for to check the given string is palindrome or not by using functional interface with lambda.

CustomFunctionalInteface.java

package com.samplecoder.lambda;

@FunctionalInterface
public interface CustomFunctionalInteface {
	public String reverse(String arg);
}

CustomFunctionalInterfaceMain.java

package com.samplecoder.lambda;

public class CustomFunctionalInterfaceMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		CustomFunctionalInteface customFunInterface = (arg) -> {
			StringBuilder builder = new StringBuilder(arg);
			return builder.reverse().toString();
		};
		
		System.out.println("MADAM IS " + ("MADAM".contentEquals(customFunInterface.reverse("MADAM")) ? "PALINDROME":"NOT PALINDROME"));
		
		System.out.println("SCHOOL IS " + ("SCHOOL".contentEquals(customFunInterface.reverse("SCHOOL")) ? "PALINDROME":"NOT PALINDROME"));
		
	}

}

Result

MADAM IS PALINDROME
SCHOOL IS NOT PALINDROME