0

Create Your Own Functional Interface in Java 8

What is a Functional Interface?

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.

If you are using some platform for continuous inspection of code quality like SonarQube, you may have noticed the following message:

java8-annotation-needed-functional-interface-001

To fix this, simply annotate the interface with @FunctionalInterface.

For example,

Sample Usage

The codes below uses your own Functional Interface

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