Java 8 Functional Interface

In this post we will explain the new feature in Java 8 Functional interface. A functional interface is an interface which only contains one abstract method but can contain default methods. Examples of an functional interface are Comparable, FileFilter and Runnable. In Java 8 and onwards, functional interfaces can be expressed using lambda expressions.

Java 8 Functional Interface

How to define a Functional Interface

To define a functional interface, you need to create an interface with one abstract method and add the following annotation to the class@FunctionalInterface. However, its not mandatory to use this interface.

Adding more than one abstract method will result in a compilation error.

How to use a functional interface

The example below will build on the defined interface above.

As you can see 3 operations have been defined add, minus and divide all using the functional interface. The amazing thing is now we can assign the function to a variable such as addFunction and then pass that to a method printResult(). Running the above produces the following output:

Comparison before Java 8

Lets take another example pre and post Java 8 to see the benefits of functional interfaces and lambda expressions.

To use the Runnable interface before Java 8 you would of needed to do the following:

The equivalent in Java 8 and onwards will be:

Thats the power of functional interfaces with lambda expressions.

Built in Functions

In Java 8 the package: java.util.function contains a set of ready made functions for you to use such as:

  • Predicate: This take one input and returns a boolean.

  • Function: This take one input and returns another

  • Supplier: This takes no arguments but returns an object

  • Consumer: This takes one argument and returns nothing.

This is a small subset of the complete functional interfaces defined in the package.

Similar posts

  1. Java 8 Stream reduce example
  2. Java 8 Stream map example
  3. ExecutorService examples in Java
  4. How to read a CSV file in Java

References

  1. Java 8 API Documentation

Leave a Reply