Functional Interface

  • A functional interface is one that contains only one abstract method. They can have only one functionality to exhibit.
  • A functional interface can contain any number of default methods.
  • In other words, it is Single Abstract Method Interfaces or SAM Interfaces.
  • It’s a new feature introduced in Java, which helps to achieve a functional programming approach.
  • Runnable, Action Listener, Comparable are some of the examples of functional interfaces.
  • @FunctionalInterface annotation ensures that the functional interface can’t have more than one abstract method. Its use is optional, but it’s best practice to use it with functional interfaces to avoid the addition of extra methods accidentally. If the interface has annotation and we try to have more than one abstract method, it throws a compiler error.
  • Some built-in functional interfaces –
    • Predicate –
      • The Predicate interface has an abstract method test which gives a Boolean value as a result of the specified argument.
      • Syntax – public interface Predicate { public boolean test(T t); }
    • BinaryOperator
      • The BinaryOperator interface contains an abstract method apply which takes two arguments and returns a result of the same type.
      • Syntax – public interface BinaryOperator { public T apply(T x, T y); }
    • Function –
      • The Function interface contains an abstract method apply which takes an argument of type T and returns a result of type R.
      • Syntax – public interface Function { public R apply(T t); }
//Custom Interface

@FunctionalInterface
interface sayable{
	void say(String msg);
}

public class FIdemo implements sayable {
	public void say(String msg) {
		System.out.println(msg);
	}
	public static void main(String args[]) {
		FIdemo demo = new FIdemo();
		demo.say("Hello There!!");
	}
}
//Built-in Interface

List<String> names = Arrays.asList("A", "B", "C");
Predicate<String> p = (s) -> s.startsWith("G");
for(String n:names) {
	if(p.test(n)) System.out.println(n);
}