What is a Functional Interface?
[wp_ad_camp_1]
Java 8 offers Lambda expressions to help us write better, and concise codes. Lambda expressions revolve around Functional Interfaces. So, what are Functional Interfaces?
The simplest definition is:
Functional Interfaces are Java Interfaces with only a single abstract method.
1 2 3 4 5 | package lambda.example; public interface DisplayOnly { public void print(); } |
If you are using some platform for continuous inspection of code quality like SonarQube, you may have noticed the following message:
1 | Annotate the "DisplayOnly" interface with the @FunctionalInterface annotation (sonar.java.source not set. Assuming 8 or greater.) |
[wp_ad_camp_2]
To fix this, simply annotate the interface with @FunctionalInterface
.
For example,
1 2 3 4 5 6 | package lambda.example; @FunctionalInterface public interface DisplayOnly { public void print(); } |
Sample Usage
The codes below uses your own Functional Interface
[wp_ad_camp_3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package lambda.example; public class DemoDisplayOnly { public static void main(String[] args) { DemoDisplayOnly demo = new DemoDisplayOnly(); demo.processSomething(() -> System.out.println("Display message to console!")); } public void processSomething(DisplayOnly displayOnly) { // Do something here // ... displayOnly.print(); } } |
Use Java 8’s core Functional Interfaces
In most cases, you would need to create your own Functional Interfaces. Java provides several Functional Interfaces that we can use.
Predicate<T>
Consumer<T>
Function<T,R>
Supplier<T>
UnaryOperators<T>
BinaryOperator<T>
Which one can we replace our DisplayOnly
interface with? Consumer<T>
!
Here’s the updated DemoDisplayOnly.java
[wp_ad_camp_4]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package lambda.example; import java.util.function.Consumer; public class DemoDisplayOnly { public static void main(String[] args) { DemoDisplayOnly demo = new DemoDisplayOnly(); demo.processSomething((x) -> System.out.println(x)); } public void processSomething(Consumer<String> displayOnly) { // Do something here // ... displayOnly.accept("Display message to console!"); } } |