Software Development

Create Your Own Functional Interface in Java 8

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.

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

[wp_ad_camp_2]

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

For example,

Sample Usage

The codes below uses your own Functional Interface

[wp_ad_camp_3]

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]

 

2162 total views , 1 views today

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like