A Functional Interface is an interface that contains only one (abstract) method inside.
It is also known as Single Abstract Method Interfaces or SAM Interfaces.
This is a feature from Java 8, which helps to achieve a functional programming approach.
Also, it is still a Functional Interface if there is an abstract method and there are several default/static methods inside that interface.
There is an annotation as “@FunctionalInterface” which guarantees the interface remains a Functional Interface (if another abstract method is added, the compiler gives an error as “Invalid ‘@FunctionalInterface’ annotation; A is not a functional interface”).
This annotation is optional but it should be used for best practices.
There is a package called java.util.function that contains some generic Functional Interfaces.
interface Supplier — — T get()
interface Consumer — — void accept(T t)
interface BiConsumer<T,U> — — void accept(T t, U u)
interface Predicate — — boolean test(T t)
interface Function — — R apply(T t)
interface BiFunction — — R apply (T t, U u)
Some Functional Interface examples from java.util.function package can be seen below.
package functionalInterfaces;
import java.util.function.*;
public class Application {
public static void main(String[] args) {
// *** interface Supplier<T> --- T get()
Supplier<Integer> s = () -> {
return 5;
};
System.out.println(s.get());// 5
// *** interface Consumer<T> --- void accept(T t)
Consumer<String> c = (str) -> System.out.println(str);
c.accept("Hi there");
// *** interface BiConsumer<T,U> --- void accept(T t, U u)
BiConsumer<String, String> bc = (str1, str2) -> System.out.println(str1 + " " + str2);
bc.accept("Hello", "World");
// *** interface Predicate<T> --- boolean test(T t)
Predicate<String> p = (str) -> str.contains("ext");
System.out.println(p.test("Test Text")); // true
// *** interface Function<T,R> --- R apply(T t)
Function<String, String> f = (str) -> {
return str.substring(0,3);
};
System.out.println(f.apply("The Forest")); // The
// *** interface BiFunction<T,U,R> --- R apply (T t, U u)
BiFunction<String, String, String> bf = (str1, str2) -> {
return str1 + " " + str2;
};
System.out.println(bf.apply("Hello", "World")); // Hello World
}
}
This is the end of the article. Please also check my other articles, here.
Thanks for reading.