Java 8: Function Interface

Java 8

If in previous article you can find some examples about Lambda expressions in Java8, this article will still talk about new feature in Java 8, Function interface.

If you are exploring the APIs to be part of Java 8 and especially those APIs which support lambda expressions you will find few interfaces like Function, Supplier, Consumer, Predicate and others which are all part of the java.util.function package, being used extensively. These interfaces have one abstract method, which is overridden by the Lambda expression defined. Let me explain about Function interface in brief and it is one of the interfaces present in java.util.function package.

Function interface has 4 methods:

In this tutorial I would like to write about the apply(T t) method, creating APIs which accept these interfaces and parameters and then invoke their corresponding methods. We will also look at how the caller of the API can pass in a Lambda expression in place of an implementation of the interface. Apart from passing a Lambda expression, the users of the API can also pass method references.

Function interface is uses in cases where you want to encapsulate some code into a method which accepts some value as an input parameter and then returns another value after performing required operations on the input. The input parameter type and the return type of the method can either be same or different.

Lets look at a class below which accepts an implementation of Function interface:

Below is the main method which will invoke the class above:

You can see that the Lambda expressions being created accept one parameter and return some value.

Following is the complete code of above sample:

After you execute sample code above, you can execute it and will get the output as follow:

Hope this useful.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*