Function Functional Interface in Java


Function Functional Interface:-

Function is an in-built functional interface which is exactly same as Predicate except that functions can return any type of result.
In other words, the Function functional interface a SAM called apply( ).
It accepts an object of any data type and returns another as a result, of any data type.

Function functional interface members:-

Function contains 4 methods and they are:-

     1) apply( )
     2) compose( )
     3) andThen( )
     4) identity( )

The method apply( ) is an abstract method while others are default and static.

Prototype of apply( ):- Following is the complete prototype of the method apply( ) as declared in the interface Function.

      public interface Function<T, R>
      {
           public <R> apply(T parameter);
      }

As we can observe the method apply( ) accepts an argument of type T and returns a value of Type R.
T and R generics type and have to be replaced with names of actual classes while declaring Function Interface reference.
Ex:-
        Function<String, Integer> f1= ......;

In this case the argument type of apply( ) will become String and return type will be Integer.

Example:-

Suppose we want to calculate square root of an Integer.

Output:-

Square root of 10 is: 3.162277660169
Square root of  9 is: 3


Chaining Functions:-

Java allows us to join two or more Functions, just like we were able to join Predicates.
This can be done by calling the following default methods given by Function functional interface.
These methods are compose( ) and andThen( ).

Prototype of compose( ):- Following is the complete prototype of the method compose( ) as declared in the interface Function.

   default Function<V,R> compose(Function<V,T> before);

The method compose( ) returns a composed function that first applies the before function to its input, and then applies this function to the result.
Ex:-
          f3=f1.compose(f2);

The above code will create a new Function called f3 which will first call f2 and then on the return value , it will call the function f1.

Example:-

Output:-

12

Prototype of andThen( ):- Following is the complete prototype of the method andThen( ) as declared in the interface Function.

    default Function<V,R> andThen(Function<V,T> after);

The method andThen( ) returns a composed function that first applies this function to its input, and then applies the after function to the result.
Ex:-
          f3=f1.andThen(f2);

The above code will create a new Function called f3, which will first call f1 and then on the return value , it will call the function f2.

Example:-
Output:-

9                

Post a Comment

0 Comments