Java Functional Interface and Lamda Implementation
The term Java functional interface was introduced in Java 8
A functional interface in Java is an interface that contains only a single abstract (unimplemented) method.
A functional interface may have defaulted, and static methods may have an implementation, in addition to the single unimplemented method.
@FunctionalInterface
Annotation is added so that we can mark an interface as a functional interface. Even without it, your interface will be treated as functional as long as it has just one abstract method. This ensures that the interface can’t have more than one abstract method.
Here, it has only one abstract method, so that we can omit the annotation@FunctionalInterface.
Important Points/Observations for functional interface:
- A functional interface has only one abstract method, but it can have multiple default methods.
@FunctionalInterface
Annotation is used to ensure an interface can’t have more than one abstract method. The use of this annotation is optional.- The java.util.function package contains many built-in functional interfaces in Java 8.
Usages of Functional Interface
- The functional interface has been introduced in Java 8 to support the lambda expression in java 8. On the other hand, it can be said lambda expression is the instance of a functional interface.
- Java 8 Collections API has been rewritten, and a new Stream API is introduced that uses a lot of functional interfaces.
- Java 8 has defined a lot of functional interfaces in this package
java.util.function
. Some of the useful java 8 functional interfaces areConsumer
,Supplier
,Function
andPredicate
.